文件:SN.xml
<?xml version="1.0"?>
<root>
<category name="Cat1" id="C1">
<subcat name="SCName1" sid="SC1">
<prod pname='prod1' pid='p1'></prod>
<prod pname='prod2' pid='p2'></prod>
<prod pname='prod3' pid='p3'></prod>
</subcat>
</category>
</root>
我想要低于输出:
<?xml version="1.0"?>
<root>
<category name="Cat1" id="C1">
<subcat name="SCName1" sid="SC1">
<prod pname='prod1' pid='p1'></prod>
<prod pname='prod2' pid='p2'></prod>
<prod pname='prod3' pid='p3'></prod>
**<prod pname='prod4' pid='p4'></prod>**
</subcat>
</category>
</root>
请帮助我使用模块获得此输出。
提前致谢。
答案 0 :(得分:4)
使用XML::XSH2,XML::LibXML的包装:
open SN.xml ;
$p := insert element prod append /root/category/subcat ;
set $p/@pname 'prod4' ;
set $p/@pid 'prod4' ;
save :b ;
答案 1 :(得分:0)
您可以使用XML :: DOM在subcat元素中附加值。
#!/usr/bin/perl
use strict;
use warnings;
use XML::DOM;
use File::Temp qw(tempfile);
my $str = <<F;
<?xml version="1.0"?>
<root>
<category name="Cat1" id="C1">
<subcat name="SCName1" sid="SC1">
<prod pname='prod1' pid='p1'></prod>
<prod pname='prod2' pid='p2'></prod>
<prod pname='prod3' pid='p3'></prod>
</subcat>
</category>
</root>
F
my ($fh, $filename) = tempfile();
print $fh $str;
close $fh;
my $parser = XML::DOM::Parser->new;
my $doc = $parser->parsefile($filename);
unlink $filename;
my $subcat = $doc->getElementsByTagName('subcat')->item(0);
my $prod = $doc->createElement('prod');
$prod->setAttribute(pname=>'prod4');
$prod->setAttribute(pid=>'p4');
$subcat->appendChild($prod);
print $doc->toString;
__END__
这给出了输出:
<?xml version="1.0"?>
<root>
<category name="Cat1" id="C1">
<subcat name="SCName1" sid="SC1">
<prod pname="prod1" pid="p1"/>
<prod pname="prod2" pid="p2"/>
<prod pname="prod3" pid="p3"/>
<prod pname="prod4" pid="p4"/></subcat>
</category>
</root>
注意!正如您可能看到缩进有一点问题,我不知道如何快速修复它。