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

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

问题描述

我的XML文件如下所示:

 < doc> 
< RU1>
< conf>
< prop name =aval =http://a.org/a.html>
< / conf>
< / RU1>
< ; RAU1>

< / conf>
< / RAU1>
< RU2>
< conf>
< prop name =aval =http://a.org/a.html>
< / conf>
< / RU2>
< ; / doc>

我想在prop字段的值中替换a.org在所有以perl开头的父母标签下,用b.com。我如何获得更改为一个xml文件? 解决方案

假设您的XML格式正确(不是),您可以使用 CPAN模块的数量,其中大部分将涉及解析文档,查找XPath查询,然后再打印出来。



 #!/下面是一个使用XML :: Twig的例子,我不得不修复XML来解析。 usr / bin / perl 

使用strict;
使用警告;

使用XML :: Twig;

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

$ twig-> print;


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


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>

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?

解决方案

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.

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天全站免登陆