Iterating over nodes using XML :: LibXML

I am using XML :: LibXML (Ver: 1.70).

My input xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<Equipment xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Equipments>
    <ECID logicalName="SysNameAlpha" id="0"/>
    <ECID logicalName="SysNameBeta" id="1"/>
  </Equipments>
</Equipment>

and my Perl script:

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

foreach my $camelid ($root->findnodes('Equipments')) {
    my $name =  $camelid->findvalue('ECID/@logicalName');
    my $id =  $camelid->findvalue('ECID/@id');
    print $name;
    print " = ";
    print $id;
    print ";\n";
}

The output I get is:

SysNameAlphaSysNameBeta = 01;

But I need the output as follows:

SysNameAlpha = 0;    
SysNameBeta = 1;

How can i achieve this?

+3
source share
1 answer

Only one Equipmentsnode, so you can only get one $camelidfor scanning. To fix this, you can make a little difference, say, for enumerating equipment / ECID:

foreach my $camelid ( $root->findnodes('Equipments/ECID') ) {
    my $name =  $camelid->findvalue('@logicalName');
    my $id =  $camelid->findvalue('@id');
    ...
}
+12
source

All Articles