开发者

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> 


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜