I want to parse XML files using xPaths. After getting a node I may need to perform xPath searches on their parent nodes. My current code using XML::XPath is:
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";
}
}
}
My goal is to get a hash of foo elements names and their bar child nodes values, if a foo does not have a bar node it should get the one from 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 parent node:
Can't call method "getNodeType" on an undefined value
Any help will be much appreciated!