如何使用 XPath 和 Perl 检索属性
我有以下 XML 结构:
<RECORD>
<TYPE ID="check_ping">
<HOSTS>
<HOST H="192.168.0.1" W="50,1%" C="100,1%" />
<HOST H="192.168.0.2" W="50,1%" C="70,1%" />
</HOSTS>
</TYPE>
<TYPE ID="check_ssh">
<HOSTS>
<HOST H="192.168.0.3" P="21"/>
<HOST H="192.168.0.4" P="21"/>
<HOST H="192.168.0.4" P="21"/>
</HOSTS>
</TYPE>
....
</RECORD>
我还有一个 Perl 脚本,应该读取该 XML,我正在使用 XML::XPath 模块。
use XML::XPath;
#.....
my $xp = XML::XPath->new(filename => 'test.xml');
#RETRIEVE ALL HOSTS WITH CHECK_SSH
my $querysshh = '/RECORD/TYPE[@ID="check_ssh"]/HOSTS/HOST';
$nodeset = $xp->find($querysshh);
foreach $mynode ($nodeset->get_nodelist) {
#HOW DO I RETRIEVE ATTRIBUTES NOW?
}
#.....
如何检索这些节点的属性?例如,如果我想阅读 H 和 P 我需要做什么?我查看了模块文档,但找不到任何有用的方法。
I have the following XML structure:
<RECORD>
<TYPE ID="check_ping">
<HOSTS>
<HOST H="192.168.0.1" W="50,1%" C="100,1%" />
<HOST H="192.168.0.2" W="50,1%" C="70,1%" />
</HOSTS>
</TYPE>
<TYPE ID="check_ssh">
<HOSTS>
<HOST H="192.168.0.3" P="21"/>
<HOST H="192.168.0.4" P="21"/>
<HOST H="192.168.0.4" P="21"/>
</HOSTS>
</TYPE>
....
</RECORD>
I have also a Perl script that is supposed to read that XML, I am using XML::XPath module.
use XML::XPath;
#.....
my $xp = XML::XPath->new(filename => 'test.xml');
#RETRIEVE ALL HOSTS WITH CHECK_SSH
my $querysshh = '/RECORD/TYPE[@ID="check_ssh"]/HOSTS/HOST';
$nodeset = $xp->find($querysshh);
foreach $mynode ($nodeset->get_nodelist) {
#HOW DO I RETRIEVE ATTRIBUTES NOW?
}
#.....
How can I retrieve the attributes of those nodes? For example if I want to read H and P what do I need to do? I looked at the module documentation but I couldnt find any useful method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
$myNode->getAttribute("H")
是否有效。Try whether
$myNode->getAttribute("H")
works.正如 Martin 所指出的,
getAttribute
方法应该可以正常工作。您可以在 XML::XPath:: 中找到其他可用方法Node::Element 文档。As Martin has pointed out, the
getAttribute
method should work fine. You can find other available methods in XML::XPath::Node::Element documentation.