Iterating over nodes using XML::LibXML

前提是你 提交于 2019-12-01 05:54:42

问题


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

My xml input file looks like this:

<?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 want output like this:

SysNameAlpha = 0;    
SysNameBeta = 1;

How can I achieve this?


回答1:


There's only one Equipments node, hence you only get one $camelid to scan. To remedy, you might change things slightly, say, to iterate over Equipment/ECIDs:

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


来源:https://stackoverflow.com/questions/5894789/iterating-over-nodes-using-xmllibxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!