作为xml twig的新手,如何在xml-twig中的两个元素之间添加空格?
输入:
<xml>
<fig id="fig6_4">
<label><xref ref-type="page" id="page_54"/>[Figure 4]</label>
<caption>The Klein Sexual Orientation Grid</caption>
</fig>
</xml>脚本:
$xml_twig_content = XML::Twig->new(
twig_handlers => {
'fig' => \&figure,
},
);
$xml_twig_content->parsefile('sample.xml');
sub figure{
my ($xml_twig_content, $figure) = @_;
my @figchild = $figure->children;
foreach my $chid (@figchild){
if ($chid->name =~ /label/){
my $t = $chid->text;
$chid->set_inner_xml($t . ' ');
$chid->erase;
}输出:
<xml>
<fig id="fig6_4">
[Figure 4] <caption>The Klein Sexual Orientation Grid</caption>
</fig>
</xml>我需要:
<xml>
<fig id="fig6_4">
<xref ref-type="page" id="page_54"/>[Figure 4] <caption>The Klein Sexual Orientation Grid</caption>
</fig>
</xml>如何在两个元素之间插入空格.....
发布于 2012-12-26 20:27:17
我将在fig/label上使用一个处理程序,因为这是唯一需要修改的元素。然后,处理程序中的代码需要在元素后面加上空格,然后删除标记:
XML::Twig->new( twig_handlers => { 'fig/label' => sub { $_->suffix( ' ')->erase; }});发布于 2012-12-26 18:04:43
我不清楚它的确切目标是什么-您的输出数据格式看起来并不是特别理想。尽管如此,下面的示例应该足以让您上路。它涉及两点:
当前输出中缺少'xref‘的文档。
顺便说一句:我以前没有使用过XML::Twig;如果您熟悉documentation的概念,那么它实际上相当不错。
use strict;
use warnings;
use XML::Twig;
my $twig = XML::Twig->new(
twig_handlers => {
'fig' => \&figure
},
pretty_print => 'indented',
);
$twig->parse(do { local $/; <DATA> });
$twig->print;
sub figure {
my ( $twig, $figure ) = @_;
# Find all children of type label (would there really be more than 1??)
foreach my $label ($figure->children('label')) {
# Replace the label with its chidren nodes
$label->replace_with($label->cut_children);
# Find the caption and place 4 spaces before it
if (my $caption = $figure->first_child('caption')) {
my $some_whitespace = XML::Twig::Elt->new('#PCDATA' => ' ');
$some_whitespace->paste(before => $caption);
}
}
}
__DATA__
<xml>
<fig id="fig6_4">
<label><xref ref-type="page" id="page_54"/>[Figure 4]</label>
<caption>The Klein Sexual Orientation Grid</caption>
</fig>
</xml>https://stackoverflow.com/questions/14036655
复制相似问题