【发布时间】:2018-02-17 11:26:19
【问题描述】:
我有以下代码可以擦除肥皂信封和正文以及保持根的 XML 字符串,我想获取最终输出并发送到 JSON。 -谢谢
use XML::Twig;
use JSON;
$xml = '<soap:Envelope><Servers>10.20.200.11</Servers></soap:Envelope>';
my $twig = XML::Twig->new( twig_roots => { Servers => 1 },
twig_handlers => {
'soap:Envelope' => sub { $_->erase() },
},
pretty_print => 'indented',
);
$twig->parse($xml);
my $output = $twig->print;
$json = JSON->new->allow_nonref;
$pretty_printed = $json->pretty->encode($output); # <-- This dosen't work!!
# finally print json
print $pretty_printed;
So if the XML looks like this - I added a node
$xml = '<Envelope><Servers><Server>10.20.200.11</Server></Servers></Envelope>';
I would expect the JSON to look like this
{
"Servers" : {
"Server" : "10.20.200.11"
}
}
【问题讨论】:
-
请始终在您的 Perl 代码中使用
use strict和use warnings。尤其是在这里寻求帮助时。 -
$twig->print打印树枝或树的字符串化 XML 版本,并返回$twig对象本身。所以你将$twig分配给$output。然后将该对象传递给 JSON,它无法转换它,因为它不知道如何处理一个有福的数据结构(即一个对象)。 XML 比 JSON 复杂得多,它有一个额外的维度。对于您的示例,已经有几种方法可以在 JSON 中对其进行编码。你希望它如何映射?