How to use XML :: XPath to get the parent node?

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);
# 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 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!

+3
source share
2

Chas, XML:: XPath ( ). find * node, , $FooName.

, , (getNodeType , , node).

, , , :

#!/usr/bin/perl

use strict;
use warnings;

use XML::XPath;

my $xp = XML::XPath->new(filename => "$0.xml");
# 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;
        my $Bar = $xp->findvalue('bar', $context); # or $context->findvalue('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->getName,"\n\n";
        }
    }
}

, : XML::XPath , , , XML::LibXML. .

+4

undef. undef , .

$xp = XML::XPath->new( context => $context );

$xp = XML::XPath->new( context => $context )
    or die "could not create object with args ( context => '$context' )";
+5

Source: https://habr.com/ru/post/1709976/


All Articles