[英]Perl script to parse XML using XML::Simple
I am trying to parse the following XML. 我正在尝试解析以下XML。 The problem is I get nothing in the output:
问题是我在输出中什么也没得到:
XML file: XML档案:
<response>
<response-name>SendUnitaryResponse</response-name>
<params>
<request-status>OK</request-status>
<unitary-request-id>B4004A3E</unitary-request-id>
</params>
</response>
Script: 脚本:
use XML::Simple;
use Data::Dumper;
my $access = XMLin('C:\Users\s.baccar\Desktop\access.log');
print $access->{response}->{response-name};
As Sobrique points out, XML::Simple isn't that simple. 正如Sobrique所指出的,XML :: Simple并不是那么简单。 In this case, it removes the root element (
<response>
), which is why your print statement fails. 在这种情况下,它将删除根元素(
<response>
),这就是您的打印语句失败的原因。 You can either change your print: 您可以更改打印:
print $access->{response-name};
...or tell XML::Simple to keep the root element: ...或告诉XML :: Simple保留根元素:
my $access = XMLin('C:/Users/s.baccar/Desktop/access.log', KeepRoot => 1);
...or best of all, use a different module. ...或者最重要的是,请使用其他模块。
XML::Simple
- isn't. XML::Simple
不是。 It's for simple XML. 它用于简单的XML。
In it's documentation it says: 在文档中说:
The use of this module in new code is discouraged.
不建议在新代码中使用此模块。 Other modules are available which provide more straightforward and consistent interfaces.
提供了其他模块,这些模块提供了更加直接和一致的界面。
Instead, I like XML::Twig
(other options exist): 相反,我喜欢
XML::Twig
(存在其他选项):
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $xml = q{<response>
<response-name>SendUnitaryResponse</response-name>
<params>
<request-status>OK</request-status>
<unitary-request-id>B4004A3E</unitary-request-id>
</params>
</response>};
my $twig_parser = XML::Twig -> new -> parse ( $xml );
#in XML::Twig - root is the 'top' node, e.g. <response> in this case.
print $twig_parser -> root -> first_child_text('response-name');
This also works if you give it a filename: 如果给它一个文件名,这也可以:
my $twig_parser = XML::Twig -> new -> parsefile ( 'C:\Users\myuser\Documents\test.xml' );
print $twig_parser -> root -> first_child_text('response-name');
In addition to what other people have said, please use strict;
除了别人说的以外,请
use strict;
( and use warnings;
) (并
use warnings;
)
If I add those to your script, I get: 如果将这些添加到您的脚本中,则会得到:
Bareword "response" not allowed while "strict subs" in use at x.pl line 8.
Bareword "name" not allowed while "strict subs" in use at x.pl line 8.
( Note that line 8 is print $access->{response}->{response-name};
) (请注意,第8行是
print $access->{response}->{response-name};
)
That line is effectively being turned into print $access->{response}->{0};
该行实际上已变为
print $access->{response}->{0};
You need to use 'response-name'
. 您需要使用
'response-name'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.