使用xml :: Twig返回整个标记

时间:2012-07-17 19:53:53

标签: xml perl xml-twig

如何使用xml :: twig返回整个xml标记并将其保存到array:

例如:

my @array=();
my $twig = XML::Twig->new(
twig_handlers => {
'data'=> sub {push @array, $_->xml_string;}

});

此代码返回所有嵌套标记,但没有标记本身,其属性是否有一个选项,使用xml :: twig返回整个标记并将其保存为变量?

1 个答案:

答案 0 :(得分:5)

使用XML :: Twigs方法sprint代替xml_stringdocs说:

  

xml_string @optional_options

Equivalent to $elt->sprint( 1), returns the string for the entire element, excluding the element's tags (but nested element tags are present)

搜索sprint函数会产生:

  

冲刺

Return the text of the whole document associated with the twig. To be used only AFTER the parse.

因此,您可以执行以下操作:

use strict;
use warnings;
use Data::Dumper;
use XML::Twig;

my @array=();
my $twig = XML::Twig->new(
twig_handlers => {
  'data'=> sub {push @array, $_->sprint;}
});

$twig->parse(qq~
  <xml>
        <data id="foo">
      <deep>
            <deeper>the deepest</deeper>
      </deep>
    </data>
  </xml>
~);

print Dumper \@array;

打印哪些:

$VAR1 = [
          '<data id="foo"><deep><deeper>the deepest</deeper></deep></data>'
        ];