gyrous
gyrous

Reputation: 209

How to ADD or Replace Specific field between specific tag which is coming in XML file using unix

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

Answers (2)

bvr
bvr

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

Michał Šrajer
Michał Šrajer

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:

  1. tag must be opened and closed in the same line
  2. no nested tag support
  3. potential conflict with characters in value and sed separator ("|" here)

For real XML processing, use real XML libraries in language you know.

Upvotes: 2

Related Questions