rob*_*lan 2 xml perl structure
我正在创建一个xml来传递给API,API返回它(数据转储):
(
"Data::Dump",
{
SiteDevices => {
"device" => {
1102 => { address => "1.2.3.4", riskfactor => "1.0", riskscore => "0.0" },
1136 => { address => "1.2.3.5", riskfactor => "1.0", riskscore => "0.0" },
20491 => { address => "1.2.3.6", riskfactor => "1.0", riskscore => "0.0" },
129644 => { address => "1.2.3.7", riskfactor => "1.0", riskscore => "0.0" },
129645 => { address => "1.2.3.8", riskfactor => "1.0", riskscore => "0.0" },
130408 => { address => "1.2.3.9", riskfactor => "1.0", riskscore => "0.0" },
135975 => { address => "1.2.3.10", riskfactor => "1.0", riskscore => "0.0" },
137642 => { address => "1.2.3.11", riskfactor => "1.0", riskscore => "0.0" },
},
"site-id" => 27,
},
success => 1,
},
)
Run Code Online (Sandbox Code Playgroud)
我想循环并打印与它们相关的设备和IP,而我在生活中无法想出任何代码来完成它.我错过了什么?!我试图循环哈希,散列哈希等等.永远不能让它工作.如果你们中的任何人有一秒钟并且可以提供答案,那么我可以羞愧地摇头,那真是棒极了.
我试过了:
foreach my $key (keys %{ $output->{‘SiteDevices’}->{‘device’} }) {
print $key
print $key->{‘address’}
}
Run Code Online (Sandbox Code Playgroud)
和
foreach my $key (keys %{ $output{‘SiteDevices’}{‘device’} }) {
print $key
print $key{‘address’}
}
Run Code Online (Sandbox Code Playgroud)
但都不起作用.
你提到这是解析的XML.它看起来像你与解析它XML::Simple和这只是不是一个好主意.
为什么不呢:
#!/usr/bin/env perl
use strict;
use warnings;
use XML::Twig;
## get xml somehow here. parsefile if it's a file already.
my $twig = XML::Twig -> new -> parse ( $your_xml );
foreach my $device ( $twig -> get_xpath('//devices' ) ) {
print $device -> att('name'), " => ";
print $device -> att('address'),"\n";
}
Run Code Online (Sandbox Code Playgroud)
这里有用的是xpath- 它不是正则表达式,但它有点类似 - 它适用于XML.在这种情况下,//device说' <device>在树中的任何地方找到一个节点.(然后我们提取属性).
这可能适用于您的方案,但您可以通过指定更长的路径来更具体:
./device - 直接位于当前节点下方. .//device - 当前节点下方的任何位置./root/SiteDevices/device - 特定匹配此"树"的节点. 您还可以使用xpath搜索属性:
.//device[@name="1136"] 会找到具有适当价值和属性的东西. 有关如何执行此操作的一些指南,请参阅XML Twig快速参考.