使用perl XML :: LibXML进行解析
|
我使用perl的
XML :: Lib
XML模块来解析来自设备的XML响应.
看来我能成功获取数据的唯一方法是修改设备的XML响应. 这是我对设备的XML响应: <chassis-inventory xmlns="http://xml.juniper.net/junos/10.3D0/junos-chassis"> <chassis junosstyle="inventory"> <name>Chassis</name> <serial-number>JN111863EAFF</serial-number> <description>VJX1000</description> <chassis-module> <name>Midplane</name> </chassis-module> <chassis-module> <name>System IO</name> </chassis-module> <chassis-module> <name>Routing Engine</name> <description>VJX1000</description> <chassis-re-disk-module> <name>ad0</name> <disk-size>1953</disk-size> <model>QEMU HARDDISK</model> <serial-number>QM00001</serial-number> <description>Hard Disk</description> </chassis-re-disk-module> </chassis-module> <chassis-module> <name>FPC 0</name> <chassis-sub-module> <name>PIC 0</name> </chassis-sub-module> </chassis-module> <chassis-module> <name>Power Supply 0</name> </chassis-module> </chassis> </chassis-inventory> 这是我用来解析和查找序列号的perl代码,例如: #!/bin/env perl
use strict;
use warnings;
use XML::LibXML;
my $f = ("/var/working/xmlstuff");
sub yeah {
my $ff;
my $f = shift;
open(my $fff,$f);
while(<$fff>) {
$_ =~ s/^s+$//;
$_ =~ s/^(<S+)s.*?=.*?((?:/)?>)/$1$2/g;
$ff .= $_;
}
close($fff);
return $ff
}
my $tparse = XML::LibXML->new();
my $ss = $tparse->load_xml( string => &yeah($f));
print map $_->to_literal,$ss->findnodes('/chassis-inventory/chassis/serial-number');
如果我不使用正则表达式替换,则不会加载任何脚本来解析. <chassis-inventory xmlns="http://xml.juniper.net/junos/10.3D0/junos-chassis"> <chassis junosstyle="inventory"> 成为这个: <chassis-inventory> <chassis> >这是XML响应还是XML :: LibXML模块的问题? 谢谢您的帮助. 解决方法
XPATH表达式失败的原因是命名空间;你需要在上下文中搜索.这是
XML::libXML documentation的解释:
要处理此问题,请注册命名空间,然后使用命名空间搜索文档.这是一个适合您的示例: #!/bin/env perl
use strict;
use warnings;
use XML::LibXML;
my $xml = XML::LibXML->load_xml( location => '/var/working/xmlstuff');
my $xpc = XML::LibXML::XPathContext->new($xml);
$xpc->registerNs('x','http://xml.juniper.net/junos/10.3D0/junos-chassis');
foreach my $node ($xpc->findnodes('/x:chassis-inventory/x:chassis/x:serial-number')) {
print $node->textContent() . "n";
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
