我有一个这样的 XML 文档:
<article>
<author>Smith</author>
<date>2011-10-10</date>
<description>Article about <b>frobnitz</b>, crulps and furtikurty's. Mainly frobnitz</description>
</article>
我需要在 Perl 中解析它,然后在一些单词或短语周围添加新标签(例如链接到定义)。我只想标记目标词的第一个实例,并将搜索范围缩小到给定标记中的内容(例如仅描述标记)。
我可以用XML::Twig解析并为描述标签设置一个“twig_handler”。但是当我调用$node->text时,我会得到删除了中间标签的文本。我真正想做的是遍历(非常小的)树,以便保留现有标签而不是破坏。因此,最终的 XML 输出应如下所示:
<article>
<author>Smith</author>
<date>2011-10-10</date>
<description>Article about <b><a href="dictionary.html#frobnitz">frobnitz</a></b>, <a href="dictionary.html#crulps">crulps</a> and <a href="dictionary.html#furtikurty">furtikurty</a>'s. Mainly frobnitz</description>
</article>
我在目标环境中也有XML::LibXML可用,但我不知道如何从那里开始......
到目前为止,这是我的最小测试用例。感谢任何帮助!
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my %dictionary = (
frobnitz => 'dictionary.html#frobnitz',
crulps => 'dictionary.html#crulps',
furtykurty => 'dictionary.html#furtykurty',
);
sub markup_plain_text {
my ( $text ) = @_;
foreach my $k ( keys %dictionary ) {
$text =~ s/(^|\W)($k)(\W|$)}/$1<a href="$dictionary{$k}">$2<\/a>$3/si;
}
return $text;
}
sub convert {
my( $t, $node ) = @_;
warn "convert: TEXT=[" . $node->text . "]\n";
$node->set_text( markup_plain_text($node->text) );
return 1;
}
sub markup {
my ( $text ) = @_;
my $t = XML::Twig->new(
twig_handlers => { description => \&convert },
pretty_print => 'indented',
);
$t->parse( $text );
return $t->flush;
}
my $orig = <<END_XML;
<article>
<author>Smith</author>
<date>2011-10-10</date>
<description>Article about <b>frobnitz</b>, crulps and furtikurty's. Mainly frobnitz's</description>
</article>
END_XML
;
markup($orig);