Search code examples
perlxml-twig

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.


Solution

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