1

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

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The reason the syntax is different for attributes and elements is that an element could have an attribute and an element with the same name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.