使用 XML::LibXML 迭代节点
我正在使用 XML::LibXML(版本:1.70)。
我的 xml 输入文件如下所示:
<?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;
但我想要这样的输出:
SysNameAlpha = 0;
SysNameBeta = 1;
我怎样才能实现这个?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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: