开发者

How do I get the entire inner content of an XML node including element tags?

开发者 https://www.devze.com 2023-01-13 19:15 出处:网络
Using XML::Twig, is there a way to get the entire HTML of a node? I do not want the text of the node, but the entire HTML with tags and all.

Using XML::Twig, is there a way to get the entire HTML of a node? I do not want the text of the node, but the entire HTML with tags and all.

input XML

<content> <p>blah blah <b> bla bla </b> </p>
<p> line 2 <i> test </i? </p>
</content>

Code

my $twig = new XML::Twig(
    TwigRoots    => {'content' => 1},
开发者_StackOverflow社区    TwigHandlers => $twig_handlers
);
my $twig_handlers = {'count/p' => \&count_ps};

sub count_ps {
    my ($twig, $test) = @_;
    $Data .= $test->text();
}

$data should show me the entire HTML.


Use the xml_string method.

my $data;
XML::Twig->new(
    twig_handlers => {
        content => sub {
            my ($twig, $elt) = @_;
            $data = $elt->xml_string;
            $twig->purge;
        }
    }
)->parse('    <content> <p>blah blah <b> bla bla </b> </p>
    <p> line 2 <i> test </i> </p>
    </content>
')->purge;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号