0

I am trying to print out content of nodes to do further process. Wanted to print x_id="123" and node "a" content. I am using XML:LibXML parser. Any suggestion? I am very new to this file parser.

Example XML:

<header>
    <id x_id="123">                            
        <a>testing</a>
        <b></b>
    </id>
</header>

Current not working code:

use strict;
use warnings;
use XML::LibXML;

my $template = "xx.xml";
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($template);
my($object) = $doc->findnodes("/header/id/");
print $doc->findvalue("/header/id/x_id");

1 Answer 1

1

Sample code snippet for demo

use strict;
use warnings;
use feature 'say';

use XML::LibXML;

my $file = 'test.xml';

my $dom = XML::LibXML->load_xml(location => $file);

foreach my $node ($dom->findnodes('//idset')) {
    say 'NodeID: ', $node->{id};
    say 'ItemA: ', $node->findvalue('./a');
    say 'ItemB: ', $node->findvalue('./b');
    say '';
}

Content of input file text.xml

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

Output

NodeID: 100
ItemA: item_a
ItemB: item_b

NodeID: 101
ItemA: item_c
ItemB: item_d
Sign up to request clarification or add additional context in comments.

7 Comments

Hi Polar Bear, tried on your code but shows "Not a HASH reference at line 12"
Line 12 is : say 'NodeID: ', $node->{id};
@toolic -- OP's data is not good example for demonstration. Only one node with confusing identification id and x_id, tags are not complaint with XML specification.
@Blurman -- What OS, perl and XML::LibXML versions are you using? In my case it is Windows 10, Strawberry perl v5.30.2, XML::LibXML 2.0203.
I am looking through the sample from [grantm.github.io/perl-libxml-by-example/basics.html] and understand how to call out the child node (title, director in the first example in the link), but no idea to call the "id" in the "movie" element.
|

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.