我有一个嵌套的XML标签,需要在Product XML
中附加PF for ExternalId输入XML:
<Products>
<Product>
<ExternalId>317851</ExternalId>
</Product>
<Product>
<ExternalId>316232</ExternalId>
</Product>
<Product>
<ExternalId>13472</ExternalId>
</Product>
</Products>
所需的输出结果:
<Products>
<Product>
<ExternalId>PF317851</ExternalId>
</Product>
<Product>
<ExternalId>PF316232</ExternalId>
</Product>
<Product>
<ExternalId>PF13472</ExternalId>
</Product>
</Products>
我尝试过使用XML Simple。
答案 0 :(得分:3)
使用模块XML::Twig
的一种方式。
script.pl
的内容:
#!/usr/bin/env perl
use warnings;
use strict;
use XML::Twig;
{
my $twig = XML::Twig->new(
twig_handlers => {
'Product/ExternalId' => sub {
$_->prefix( 'PF' );
}
},
pretty_print => 'indented',
)->parsefile( shift )->print;
}
像以下一样运行:
perl-5.14.2 script.pl xmlfile
产量:
<Products>
<Product>
<ExternalId>PF317851</ExternalId>
</Product>
<Product>
<ExternalId>PF316232</ExternalId>
</Product>
<Product>
<ExternalId>PF13472</ExternalId>
</Product>
</Products>
更新:要打印到文件,我添加了两个修改,一行打开输出文件,print
方法,输出文件的文件句柄打印为参数
结果是:
#!/usr/bin/env perl
use warnings;
use strict;
use XML::Twig;
die qq|Usage: perl $0 <input-xml> <output-xml>\n| unless @ARGV == 2;
open my $ofh, '>', pop or die qq|ERROR: Cannot open output file\n|;
{
my $twig = XML::Twig->new(
twig_handlers => {
'Product/ExternalId' => sub {
$_->prefix( 'PF' );
}
},
pretty_print => 'indented',
)->parsefile( shift )->print( $ofh );
}
它被调用如:
perl-5.14.2 script.pl xmlfile outfile