karan arora
karan arora

Reputation: 184

Delete TAG inside TAG in XML using PERL

I have following XML:

  <TRADEEXT>
    <TRADE att="err" att1="2">
      <val_1 att_01="13"/>
        <TRADE att="err1" att1="2">
          <val_1 att_01="13"/>
        </TRADE>
    </TRADE>
    <TRADE att="err12" att1="211">
      <val_1 att_01="131"/>
        <TRADE att="err11" att1="21">
          <val_1 att_01="13"/>
        </TRADE>
    </TRADE>
  </TRADEEXT>

The requirement is very simple. Need to delete all sub-trades

Hence the required output must be :

  <TRADEEXT>
    <TRADE att="err" att1="2">
      <val_1 att_01="13"/>
    </TRADE>
    <TRADE att="err12" att1="211">
      <val_1 att_01="131"/>
    </TRADE>
  </TRADEEXT>

As can be seen there is no sub-trades left.

Below is the code which I have scribbled.

#!/usr/bin/perl

use warnings;
use strict;
use XML::Twig;

use XML::Twig;
my $twig = new XML::Twig(twig_handlers => {'TRADEEXT/TRADE/TRADE' => sub { $_->delete() }});

$twig->parsefile(file_name_1.xml');
$twig->set_pretty_print('indented');

I have no idea why it's not working.

Upvotes: -1

Views: 94

Answers (2)

karan arora
karan arora

Reputation: 184

Got it fixed.Posting my answer so that it can help someone in fututre.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Twig;


my $twig = new XML::Twig( twig_handlers => { 'TRADE/TRADE' => \&TRADE } );

$twig->parsefile('FILE_NAME_1.xml');

$twig->set_pretty_print('indented');

$twig->print_to_file('out.xml');

sub TRADE {
    my ( $twig, $TRADE ) = @_;
    foreach  my $c ($TRADE) 
    {
     $c->delete($TRADE) 

      ;
    }
}

Upvotes: -1

mirod
mirod

Reputation: 16171

I guess you should add a $twig->print at the end of your code.

Upvotes: 1

Related Questions