使用XML :: Parser,它返回什么数据结构?

时间:2014-09-24 21:55:07

标签: perl xml-parsing

我试图在perl中解析一些XML,并且我很难弄清楚如何访问它。我只限于使用XML::ParserXML::Twig,因为这必须部署在大量RedHat 6系统上而不添加任何模块,因此我无法使用更方便的内容,例如{ {1}}。

问题是如何获取数据。代码的核心是:

XML::Simple

这会产生一些奇数输出(已编辑)

use XML::Parser;
use Data::Dumper;

# $response_string is a string of XML.
my $xml_parser = new XML::Parser(Style => 'Time');
my $xml_wodge = $xml_parser->parse($response_string);

# Export methods to see what this is.
print Dumper ($xml_wodge);
print "I have a ref type: ", ref($xml_wodge), "\n";
print "I have array size: ", @xml_wodge, "\n";
print "I have hash keys:  ", %xml_wodge, "\n";
print "I have string value: ", $xml_wodge, "\n";

$VAR1 = [ [valid XML dump] ]; I have reference type ARRAY I have array size: I have hash keys: I have string value ARRAY(0x22c5538) 中的值是某种东西。转储器正确地将其转储出来,但是没有一个数据结构原语我点击它似乎返回任何东西。它检测为Array,但它似乎是一个零元素数组,其中完整的XML数据结构潜伏在无法触及的范围内。

我如何联系到它?

2 个答案:

答案 0 :(得分:0)

您使用的是XML :: Parse错误。阅读the documentation

具体来说,->parse()方法并不意味着返回任何内容。它的意思是用数据填充XML :: Parse对象。然后你可以使用那个对象。

所以,你会这样做:

my $xml_parser = new XML::Parser(Style => 'Time');
$xml_parser->parse($response_string);

# .. Then use $xml_parser

答案 1 :(得分:0)

choroba在注释中是正确的,此调用返回一个数组引用。根据perlreftut,访问数组需要:

${$xml_wodge}[0]

样式语法。

XML :: Parser返回特定格式的数据结构。对于像这样的XML结构:

<Top>
  <Mid1 id="thing">
    <Leaf1>"I'm a leaf"</Leaf1>
  </Mid1>
</Top>
  • 数组索引0将是字符串&#34; Top&#34;
  • 数组索引1将是另一个数组引用。
    • [1] [0]是一个哈希引用,只有一个密钥:&#39; id&#39;价值为&#39;&#39;。
    • [1] [1]是字符串&#34; Mid1&#34;。
    • [1] [2]是另一个数组引用。

奇数索引是节名,甚至索引是对其他元素的数组引用。

对于Leaf1:

  • 数组索引0是对空哈希的哈希引用。
  • 数组索引1是字符串&#34; Leaf1&#34;。
  • 数组索引2是数组引用。
    • [..] [2] [0]是对空哈希的哈希引用。
    • [..] [2] [1]是值&#34; 0&#34;因为这个元素没有名字。
    • [..] [2] [2]是字符串&#34;我是叶子&#34;。

Leaf1的值可以通过以下方式直接访问:

${${${$xml_wodge}[1]}[2]}[2]}[2]