如何使用 Perl 查找和替换 XML 中的文本? [英] How can I find and replace text in XML using Perl?

查看:22
本文介绍了如何使用 Perl 查找和替换 XML 中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 XML 文件如下所示:

My XML file looks something like this:

<doc>
    <RU1>
       <conf> 
              <prop name="a" val="http://a.org/a.html> 
       </conf>    
    </RU1>
    <RAU1>
     <conf> 
              <prop name="a" val="http://a.org/a.html> 
       </conf>
    </RAU1>
    <RU2>
     <conf> 
              <prop name="a" val="http://a.org/a.html> 
       </conf>
    </RU2>
</doc>

我想在 perl 中以 RU 开头的所有父标记下,将 prop 字段值中的a.org"替换为b.com".如何将更改的内容作为 xml 文件获取?

I want to replace "a.org" in the value of the prop field, under all parent tags which start with RU in perl, with "b.com".How do I obtain the changed as an xml file?

推荐答案

假设您的 XML 格式正确(不是),您可以使用 许多 CPAN 模块 用于该工作.其中大部分将涉及解析文档,使用 XPath 查询查找您的位,然后再次打印文档.

Assuming that your XML is well formed (it isn't) you can use a number of CPAN modules for the job. Most of the will involve parsing the document, finding your bit with an XPath query, and printing the document out again.

这是一个使用 XML::Twig 的示例.我必须修复 XML 才能解析它.

Here's an example with XML::Twig. I had to fix up the XML to get it to parse.

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig->new(
    twig_handlers => {
        'conf/prop' => sub { $_->{att}{val} =~ s/a.org/b.org/; }
    },
    pretty_print => "indented"
);
$twig->parse(join "", <DATA>);

$twig->print;


__END__
<foo>
<RU1>
   <conf>
          <prop name="a" val="http://a.org/a.html" />
   </conf>
</RU1>
<RAU1>
   <conf>
          <prop name="a" val="http://a.org/a.html" />
   </conf>
</RAU1>
<RU2>
 <conf> 
          <prop name="a" val="http://a.org/a.html" />
   </conf>
</RU2>
</foo>

这篇关于如何使用 Perl 查找和替换 XML 中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆