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;
}
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 hashoutput