user2190101 user2190101 - 1 month ago 12x
Perl Question

perl script to iterate over xml nodes using XML::LibXML

I am trying to come up with a perl script to iterate over some nodes and get values in xml file.

My XML File looks like below and is saved spec.xml

<?xml version="1.0" encoding="UTF-8"?>
<WO xmlns="" xmlns:xsi="" >
<STARTTIME xsi:nil="true" />
<NALUE xsi:nil="true" />
<NVALUE xsi:nil="true" />

when I run the below script , I neither get the output nor any error to get clue on where to fix things...

I am not a perl expert , would love experts here to through some light...

use XML::LibXML;
use strict;
use warnings;
my $file = 'spec.xml';
my $parser = XML::LibXML->new();
my $tree = $parser->parse_file($file);
my $root = $tree->getDocumentElement;

foreach my $atrid ( $tree->findnodes('WO/WOSet/SR/SPEC') ) {
my $name = $atrid->findvalue('ATTRID');
my $value = $atrid->findvalue('AVALUE');
print $name
print " = ";
print $value;
print ";\n";

My expected output is



The XML doesn't contain any element named WO in the null namespace. You want to match the elements named WO in the namespace.


use strict;
use warnings;

use XML::LibXML               qw( );
use XML::LibXML::XPathContext qw( );

my $file = 'spec.xml';

my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($file);
my $root = $doc->getDocumentElement;

my $xpc = XML::LibXML::XPathContext->new($doc);
$xpc->registerNs(y => '');

for my $atrid ( $xpc->findnodes('y:WO/y:WOSet/y:SR/y:SPEC') ) {
    my $name  = $xpc->findvalue('y:ATTRID', $atrid);
    my $value = $xpc->findvalue('y:AVALUE', $atrid);
    print "$name = $value\n";