xmlperlxml-libxml

Perl XML get element node using XML::LibXML


I would like to replace the element node of my XML file, but I did not even succeed to get the node. My code below works for other child nodes but not the id node.

Here is my XML file:

<header>
    <idset id="100">                            
        <a>item_a</a>
        <b>item_b</b>
    </idset>
</header>

Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use XML::LibXML;

my $file = 'test.xml';
my $parser = XML::LibXML->new();
my $doc = $parser->load_xml(location => $file);

my($object11) = $doc->findnodes('/header/idset');
say 'a: ',$object11->findvalue('./a');
say 'b: ',$object11->findvalue('./b');
say 'id: ',$object11->findvalue('./id');

Current Result:

a: item_a
b: item_b
id:

Expecting Result:

a: item_a
b: item_b
id: 100

Solution

  • The id is an attribute, not an element. You need to use a different selector style in your xpath expression.

    say 'id: ',$object11->findvalue('./@id');
    

    In xpath, an attribute is targeted with @foo. See https://www.w3.org/TR/1999/REC-xpath-19991116/#path-abbrev for a short summary of this and other xpath syntax.