Delete common XML tags from second XML file while merging two XML files

179 views Asked by At

I am able to merge two XML file data with the help of XML::Twig module but in some cases there are chances of same tag appearing in both the XML files in such a situation I need to keep the data from first file intact and delete it from the second. Can someone please let me know how to achieve it via XML::Twig ?

Below is the code that I am using to merge two XML data

First XML data

<config>
    <tag1>A1</tag1>
    <tag2>A2</tag2>
</config>

Second XML data

<config>
    <tag2>A2</tag2>
    <tag3>A1</tag3>
    <opt>
        <user login="grep" fullname="BOB" />
        <user login="stty" fullname="TOM" />
    </opt>
</config>

<tag2> data appears in both files. I need to delete duplicate data from the second file.

Code

use XML::Twig;
use Data::Dumper;
use XML::Simple;

print add(
    'C:\Users\chidori\Desktop\inputfile1.xml',
    'C:\Users\chidori\Desktop\inputfile2.xml'
);

sub add {
    my $result_twig;
    my ( $XML_File1, $XML_File2 ) = @_;

    foreach my $file ( $XML_File1, $XML_File2 ) {

        my $current_twig = XML::Twig->new(
            pretty_print => 'indented',
            comments     => 'process',
        );

        $current_twig->parsefile( $file );

        if ( !$result_twig ) {
            $result_twig = $current_twig;
        }
        else {
            $current_twig->root->move( last_child => $result_twig->root )->erase;
        }
    }

    return $result_twig->sprint;
}
1

There are 1 answers

0
Borodin On BEST ANSWER

This solution works by adding the tag names of all the first-level elements to a hash %tags. When the second file is processed, each first-level element is cut and pasted into the original document if its tag name isn't already present in the hash

use strict;
use warnings;

use XML::Twig;

my %tags;

my $twig = XML::Twig->parse('inputfile1.xml');

++$tags{$_->tag} for $twig->findnodes('/config/*');


{
    my $twig2 = XML::Twig->parse('inputfile2.xml');

    for my $elem ( $twig2->findnodes('/config/*') ) {
      unless ( $tags{$elem->tag} ) {
        $elem->cut;
        $elem->paste(last_child => $twig->root);
      }
    }
}

$twig->set_pretty_print('indented');
$twig->print;

output

<config>
  <tag1>A1</tag1>
  <tag2>A2</tag2>
  <tag3>A1</tag3>
  <opt>
    <user fullname="BOB" login="grep"/>
    <user fullname="TOM" login="stty"/>
  </opt>
</config>