2012-07-17 102 views
0

返回整个标签我如何可以用XML ::嫩枝返回完整的XML标签并将其保存到数组:使用XML ::嫩枝

例如:

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

}); 

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

+0

能否请您提供一些输入工作的例子吗? – simbabque 2012-07-17 20:53:46

+0

没关系。我自己做了一些。 – simbabque 2012-07-17 21:05:02

回答

5

使用XML :: Twigs方法sprint而不是xml_string。该docs说:

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>' 
     ];