我想用xPath解析XML文件。獲得節點後,我可能需要在其父節點上執行xPath搜索。我使用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元素名稱的哈希和他們的欄子節點的值,如果FOO沒有一個杆節點就應該從其父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
當試圖獲得父節點在使用上面的代碼我得到一個錯誤:
燦」 t調用方法「getNodeType」在 未定義值
任何幫助將不勝感激!
感謝您的回答,但這不是問題。我知道我得到錯誤消息試圖調用一個undef的方法,問題是我在做什麼錯了 - 爲什麼我不能得到父節點?順便說一句,構造函數是好的,我用你的代碼,並沒有消息。 – Dror 2009-06-08 13:59:45
Offhand,我會說你的問題是,你正在通過分配$ xp第二次銷燬原始對象。 – 2009-06-08 14:47:23