나는 XML 문서를 다음과 같이 있습니다텍스트 노드에 마크 업을 추가하기 위해 Perl에서 복잡한 XML 문서를 수정하려면 어떻게해야합니까?
<article>
<author>Smith</author>
<date>2011-10-10</date>
<description>Article about <b>frobnitz</b>, crulps and furtikurty's. Mainly frobnitz</description>
</article>
내가 (예 : 정의 링크) 펄이 구문을 분석하고 어떤 단어 나 문구 주위에 새 태그를 추가해야합니다. 나는 표적 단어의 첫 번째 인스턴스에만 태그를 달고 주어진 태그에있는 것 (예 : 설명 태그 만)으로 검색 범위를 좁히고 싶습니다.
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);
나는 웹 프로그래밍에 대한 경험이 없지만 xml 안에 html을 넣는 것이 좀 이상하지 않습니까? – flies
예, 그렇습니다. 이 특정 CMS에는 HTML 하위 집합을 허용하는 DTD가 있습니다. 프로덕션 환경에서 XML은 두 번째로 변형되고 CDATA 태그 안에 HTML이 래핑됩니다. 이는 조금 더 정상입니다. – Hissohathair