如何更新XML标记的内容?

时间:2012-11-27 10:44:17

标签: xml perl

我想编写一个perl代码来替换XML中标记的内容。例如。 <A>Hello<A>

我想在XML中搜索标记<A>,然后将值“Hello”替换为“Hi”。

我该怎么做?

2 个答案:

答案 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::XSH2XML::LibXML的包装:

open file.xml ;
for //A[text()='Hello'] set text() 'Hi' ;
save :b ;