I want to parse XML files using xPaths. After receiving the node, I may need to perform an xPath search on my parent nodes. My current code using XML :: XPath :
my $xp = XML::XPath->new(filename => $XMLPath);
my $Foo = $xp->find('//foo[name] | //foos[name]');
if (!$Foo->isa('XML::XPath::NodeSet') || $Foo->size() == 0) {
return undef;
} else {
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 {
my $parent = $context->getParentNode;
print $parent->getNodeType,"\n\n";
}
}
}
My goal is to get a hash from the names of the foo elements and their values โโof the child nodes of the bar, if foo does not have a node bar, it should get one of its parent foo or foos node.
For this XML:
<root>
<foos>
<bar>GlobalBar</bar>
<foo>
<name>number1</name>
<bar>bar1</bar>
</foo>
<foo>
<name>number2</name>
</foo>
</foos>
</root>
I would expect:
number1->bar1
number2->GlobalBar
When using the above code, I get an error when trying to get the parent node:
Unable to call getNodeType method on undefined value
Any help would be greatly appreciated!
Drror source
share