我想编写一个perl代码来替换XML中标记的内容。例如。 <A>Hello<A>
。
我想在XML中搜索标记<A>
,然后将值“Hello”替换为“Hi”。
我该怎么做?
答案 0 :(得分:2)
XML::Twig
模块非常适用于此,因为它允许您指定在解析XML时遇到给定标记时执行的处理程序。
如果您提供了一些真实的XML数据作为示例,那会有所帮助,但我使用了您的问题的精确度。
use strict;
use warnings;
use XML::Twig;
my $twig = XML::Twig->new(
twig_handlers => { A => sub { $_->subs_text(qr/Hello/, 'Hi') } },
);
$twig->parse(*DATA);
$twig->print;
__DATA__
<root>
I want to replace the content of a tag in XML. e.g. In
<A>Hello</A> I want to replace the value "Hello" with "Hi".
</root>
<强>输出强>
<root>
I want to replace the content of a tag in XML. e.g. In
<A>Hi</A> I want to replace the value "Hello" with "Hi".
</root>
答案 1 :(得分:0)
使用XML::XSH2,XML::LibXML的包装:
open file.xml ;
for //A[text()='Hello'] set text() 'Hi' ;
save :b ;