Reputation: 209
I have XML file inside that file format which is given below is present
<Open>
<ID>7175</ID>
<Name>GEENU</Name>
<Description>CHUMMA</Description>
<Active>1</Active>
<Users>1</Users>
</Open>
I want to add or replace some field which is coming in specific tag. For Example, i want to add ",GEENU" next to "CHUMMA" which is present in tag.
<Open>
<ID>7175</ID>
<Name>GEENU</Name>
<Description>CHUMMA,GEENU</Description>
<Active>1</Active>
<Users>1</Users>
</Open>
Upvotes: 1
Views: 439
Reputation: 9697
Here is a solution using XML::Twig:
use XML::Twig;
my $xml = <<END_XML;
<Open>
<ID>7175</ID>
<Name>GEENU</Name>
<Description>CHUMMA</Description>
<Active>1</Active>
<Users>1</Users>
</Open>
END_XML
my $twig = XML::Twig->new(
twig_handlers => {
Description => sub {
my $text = $_->trimmed_text();
if($text eq 'CHUMMA') {
$_->set_text($text . ',GEENU');
}
},
},
pretty_print => 'indented',
);
$twig->parse($xml);
$twig->print;
It prints:
<Open>
<ID>7175</ID>
<Name>GEENU</Name>
<Description>CHUMMA,GEENU</Description>
<Active>1</Active>
<Users>1</Users>
</Open>
Upvotes: 4
Reputation: 31182
In very simple scenario, you can:
TAG="Description"
OLDVAL="CHUMMA"
NEWVAL="CHUMMA,GEENU"
sed "s|<$TAG>$OLDVAL</$TAG>|<$TAG>$NEWVAL</$TAG>|g" -i my.xml
But it have a bunch of limitations:
For real XML processing, use real XML libraries in language you know.
Upvotes: 2