本文介绍了使用XML :: LibXML遍历节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XML :: LibXML(版本:1.70).

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

我的xml输入文件如下:

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>

和我的Perl脚本:

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";
}

我得到的输出是:

SysNameAlphaSysNameBeta = 01;

但是我想要这样的输出:

But I want output like this:

SysNameAlpha = 0;
SysNameBeta = 1;

我该如何实现?

推荐答案

只有一个Equipments节点,因此只需要扫描一个$camelid.为了解决这个问题,您可以稍作更改,例如遍历设备/ECID:

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');
    ...
}

这篇关于使用XML :: LibXML遍历节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:03