Search code examples
xmlperlxml-simple

Perl code for Find and replace a tag value in XML


Below is the XML I will be using:

<a>

<id>ABC</id>

<class />

<gender />

</a>

I want to write a Perl code which search for tag 'id' and replace the value "ABC" with "DEF".

However the nesting of above XML can change. So I want to make a generalized code that search for the tag 'id' independently of its exact position.

Till now i am able to get the logic where i can replace the value in ABC but that makes my code static of the position of tag 'id'.

#!usr/bin/perl
use warnings;
use XML::Simple;
use Spreadsheet::ParseExcel;
use Data::Dumper;
my $FileName = 'sample.xls';
my $xml_file = 'hello.xml';
$par=$ARGV[0];
my $xml = XMLin($xml_file,
    KeepRoot=>1,
    ForceArray=>1,);
$xml->{a}->[0]->{id}='DEF';
XMLout(
    $xml,
    KeepRoot =>1 ,
    NoAttr =>1,
    OutputFile => $xml_file,
        );
    }

Solution

  • XPath is able to find nodes without needing to know the position in the tree.

    use strictures;
    use XML::LibXML qw();
    my $dom = XML::LibXML->load_xml(string => <<'XML');
    <a>
    <id>ABC</id>
    <class />
    <gender />
    </a>
    XML
    
    for my $id ($dom->findnodes('//id[string()="ABC"]')) {
        $id->removeChildNodes;
        $id->appendText('DEF');
    }
    
    print $dom->toString