【发布时间】:2009-06-08 12:19:54
【问题描述】:
我想使用 xPaths 解析 XML 文件。获得节点后,我可能需要在其父节点上执行 xPath 搜索。我当前使用XML::XPath 的代码是:
my $xp = XML::XPath->new(filename => $XMLPath);
# get all foo or foos node with a name
my $Foo = $xp->find('//foo[name] | //foos[name]');
if (!$Foo->isa('XML::XPath::NodeSet') || $Foo->size() == 0) {
# no foo found
return undef;
} else {
# go over each and get its bar node
foreach my $context ($Foo->get_nodelist) {
my $FooName = $context->find('name')->string_value;
$xp = XML::XPath->new( context => $context );
my $Bar = $xp->getNodeText('bar');
if ($Bar) {
print "Got $FooName with $Bar\n";
} else {
# move up the tree to get data from parent
my $parent = $context->getParentNode;
print $parent->getNodeType,"\n\n";
}
}
}
我的目标是获取 foo 元素名称及其 bar 子节点值的哈希值,如果 foo 没有 bar 节点,它应该从其父 foo 或 foos 节点获取一个。
对于这个 XML:
<root>
<foos>
<bar>GlobalBar</bar>
<foo>
<name>number1</name>
<bar>bar1</bar>
</foo>
<foo>
<name>number2</name>
</foo>
</foos>
</root>
我希望:
number1->bar1
number2->GlobalBar
使用上述代码时,我在尝试获取父节点时遇到错误:
无法调用方法“getNodeType” 未定义值
任何帮助将不胜感激!
【问题讨论】: