Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find and replace text in XML using Perl?

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?

like image 618
fixxxer Avatar asked Nov 22 '25 04:11

fixxxer


2 Answers

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>
like image 199
Schwern Avatar answered Nov 24 '25 00:11

Schwern


Grab an XML parser off the CPAN and use it. They're there for a reason.

Once you've done that, it's some fairly simple XPath expressions to get the nodes you want, and then some quick text replacement on the specific attributes themselves.

like image 27
Anon. Avatar answered Nov 23 '25 23:11

Anon.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!