0

xml :: twigを使用してxmlタグ全体を返し、それを配列に保存するにはどうすればよいですか?

例えば ​​:

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

});

このコードはネストされたすべてのタグを返しますが、タグ自体とそのプロパティは含まれていません。xml:: twigを使用してタグ全体を返し、変数に保存するオプションはありますか?

4

1 に答える 1

5

sprintの代わりにXML::Twigs メソッドを使用しますxml_stringドキュメントは次のように述べています。

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>'
        ];
于 2012-07-17T21:04:22.633 に答える