Find value of child node

Ok, this is a pretty rudimentary question, but I'm new to Perl and I honestly can't find the answer anywhere, although I'm sure it will be ridiculously simple.

Let's say I have the following XML schema:

<root>
    <parentNode status="Good">
        <A>
            <B>
                <value><![CDATA[This is my value]]</value>
            </B>
        </A>
    </parentNode>
</root>

      

Let's assume there will be several parentNodes with different statuses.

I am trying to write a script that will give me the content of each of the nodes of the parentNodes value where the status is not "good"

Using the following code, I was able to successfully get the correct parentNodes:

my $parser = XML::LibXML->new();
my $tree = $parser->parse_file($xml_file);
my $root = $tree->getDocumentElement;
my @records = $root->findnodes("//parentNode");
foreach my $node (@records) {
    my $resultAtt = $node->getAttribute('status');
    next if $resultAtt ne "Good";

      

But when I try:

my $val = $node->findvalue("value");

      

I am not getting anything.

Also, I am really interested in the "This is my value" part. When you read a value, does CDATA affect it at all?

+3


source to share


3 answers


Your XPath must be implicit.

Instead of using: my $val = $node->findvalue("value");

you should use:$val = $node->findvalue('./A/B/value');

You must have success: D



Copy the code (and commit the CDATA to close the parenthesis) and use the above code snippet instead:

$ ./test2.pl 
Found the value: This is my value
$

      

+2


source


XPath

value

      

not suitable for

child::value

      



which means looking for a node with a name value

that is a child of the context node. If you want to find a descendant, you want

descendant::value

      

which means people write like

.//value

      

+1


source


This is done very simply by creating an appropriate XPath expression to find the elements value

you want

use strict;
use warnings;

use XML::LibXML;

my $xml = XML::LibXML->load_xml(IO => \*DATA);

for my $value ($xml->findnodes('/root/parentNode[@status != "Good"]//value') ) {

  print $value->textContent, "\n";
}


__DATA__
<root>
    <parentNode status="Good">
        <A>
            <B>
                <value><![CDATA[This is my value]]></value>
            </B>
        </A>
    </parentNode>
    <parentNode status="Not Good">
        <A>
            <B>
                <value><![CDATA[This is another value]]></value>
            </B>
        </A>
    </parentNode>
</root>

      

Output

This is another value

      

0


source







All Articles