[英]Delete common XML tags from second XML file while merging two XML files
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. 我可以借助XML :: Twig模块合并两个XML文件数据,但在某些情况下,在这种情况下,两个XML文件中都可能出现相同的标签,因此我需要保持第一个文件中的数据完整并删除从第二个开始。 Can someone please let me know how to achieve it via XML::Twig
? 有人可以让我知道如何通过XML::Twig
实现它吗?
Below is the code that I am using to merge two XML data 下面是我用来合并两个XML数据的代码
First XML data 第一个XML数据
<config>
<tag1>A1</tag1>
<tag2>A2</tag2>
</config>
Second XML data 第二个XML数据
<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. <tag2>
数据出现在两个文件中。 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
. 该解决方案通过将所有第一级元素的标签名称添加到哈希%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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.