你得到findnodes_as_string
的只是一个字符串,它不再HTML::Element
是保存文档的对象的一部分。如果您希望能够输出对象,则需要更新对象本身。
你需要使用findnodes
来获取元素(你得到一个匹配元素的列表,取该列表中的第一个),然后你可以使用replace_with
. 如果包含标记(即,如果它不是简单的文本内容) ,您可能需要将HTML::Element
对象传递给。replace_with
$newhtml
#!/usr/bin/perl
use strict;
use warnings;
use HTML::TreeBuilder::XPath;
my $html=q{<html><head><title>foo</title></head>
<body><div id="title">foo</div>
<div id="content"><p>1 para</p><p>2 para's</p></div>
</body>
</html>};
my $new_content='<div id="content"><p>new para 1</p><p>new para 2</p></div>';
my $tree= HTML::TreeBuilder::XPath->new();
$tree->parse_content($html);
# findnodes erturns a list of elements, take the first one
my $div = ($tree->findnodes('//div[@id="content"]'))[0];
# replace the div with an element created from $new_content
$div->replace_with( HTML::TreeBuilder->new_from_content( $new_content));
print $tree->as_HTML;