【发布时间】:2015-11-25 19:26:43
【问题描述】:
我有一个 XML(示例)文件:test.xml
<root>
<tag1>AAA</tag1>
<tag2>BBB</tag2>
<tag3>
<tag4>DDD</tag4>
</tag3>
</root>
我想要达到的结果是,设置两个变量(来自输入):即:
my $xpath = '/root/tag3/tag4'; # or '/root/tag2/tag5' or '/root/tag6'
my $xvalue = 'CCC'; # or 'EEE'
脚本会检查 $xpath 变量,如果它存在于 XML 文件中,那么它会更改它的文本。如果 XML 文件中不存在,则使用 $xpath 和 $xvalue 创建元素。
我使用下面的脚本来设置 $xpath 的文本,但是如何修改它以便它可以根据 $xpath 的存在做正确的事情?非常感谢,
open( my $output, '>', "$ofile") or die "cannot create $ofile: $!";
XML::Twig->new( twig_roots => { "$xpath" =>
sub { my $text= $_->text();
$_->set_text($xvalue);
$_->flush;
},
},
twig_print_outside_roots => $output,
pretty_print => 'indented',
)
->parsefile( "test.xml" );
【问题讨论】:
标签: xml perl perl-module xml-twig