【发布时间】:2016-02-25 13:39:17
【问题描述】:
我正在尝试将 xml 文件拆分为多个格式正确的片段,an ancient PerlMonks solution 在 XML::Twig 的帮助下做得很好数据输入。
如果我通过重新组合节点以过滤到父节点来使数据结构稍微复杂一点,则第二个文件的格式不正确:父节点缺少其开始标记。我很迷茫,找不到原因。
SSCCE(与初始示例的区别在于包含<thing> 的<thing_list>):
use XML::Twig;
use IO::Tee;
use feature 'say';
open my $frufile, '>', 'fruit.xml' or die "fruit $!";
open my $vegfile, '>', 'veg.xml' or die "veg $!";
my $tee = IO::Tee->new($frufile, $vegfile);
select $tee;
my $twig=XML::Twig->new(
twig_handlers => {
thing => \&magic,
_default_ => sub {
say STDOUT '_default_ for '.$_->name;
$_[0]->flush($tee); #default filehandle = tee
1;
},
},
pretty_print => 'indented',
empty_tags => 'normal',
);
$twig->parse( *DATA );
sub magic {
my ($thing, $element) = @_;
say STDOUT "magic for ". $element->{att}{type};
for ($element->{att}{type}) {
if (/fruit/) {
$thing->flush($frufile);
} elsif (/vegetable/) {
$thing->flush($vegfile);
} else {
$thing->purge;
}
}
1;
}
__DATA__
<batch>
<header>
<foo>1</foo>
<bar>2</bar>
<baz>3</baz>
</header>
<thing_list>
<thing type="fruit" >Im an apple!</thing>
<thing type="city" >Toronto</thing>
<thing type="vegetable" >Im a carrot!</thing>
<thing type="city" >Melrose</thing>
<thing type="vegetable" >Im a potato!</thing>
<thing type="fruit" >Im a pear!</thing>
<thing type="vegetable" >Im a pickle!</thing>
<thing type="city" >Patna</thing>
<thing type="fruit" >Im a banana!</thing>
<thing type="vegetable" >Im an eggplant!</thing>
<thing type="city" >Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu</thing>
</thing_list>
<trailer>
<chrzaszcz>A</chrzaszcz>
<zdzblo>B</zdzblo>
</trailer>
</batch>
虽然第一个fruit.xml 没问题:
<batch>
<header>
<foo>1</foo>
<bar>2</bar>
<baz>3</baz>
</header>
<thing_list>
<thing type="fruit">Im an apple!</thing>
<thing type="fruit">Im a pear!</thing>
<thing type="fruit">Im a banana!</thing>
</thing_list>
<trailer>
<chrzaszcz>A</chrzaszcz>
<zdzblo>B</zdzblo>
</trailer>
</batch>
veg.xml 缺少<thing_list> 的开始标签
<batch>
<header>
<foo>1</foo>
<bar>2</bar>
<baz>3</baz>
</header>
<thing type="vegetable">Im a carrot!</thing>
<thing type="vegetable">Im a potato!</thing>
<thing type="vegetable">Im a pickle!</thing>
<thing type="vegetable">Im an eggplant!</thing>
</thing_list>
<trailer>
<chrzaszcz>A</chrzaszcz>
<zdzblo>B</zdzblo>
</trailer>
</batch>
我还注意到,如果我将<thing_list>标签注释到数据中,则veg.xml中也缺少与开始标签相对应的注释,但fruit.xml中没有...
我似乎明白在处理第一个 <thing> 时会出现第一个评论,而在处理文件的其余部分时应该从 _default_ 处理程序处理第二个评论。但是我不明白<thing_list>没有评论时是否相同。
WFIW,我在 Windows 7 机器上使用 Strawberry 的 Perl 5.20.1
【问题讨论】:
-
可以在 Linux 上重现
-
@ikegami 你的意思是“不能复制”?
-
不,没有错字。我写的是我的意思。
-
@ikegami 感谢您花时间进行测试。所以它要么坏了,要么我更可能误解了 XML::Twig 的用法
标签: xml perl xml-parsing xml-twig