![](/img/trans.png)
[英]Merging two xml files with python if a tag is contained on a second file
[英]Delete common XML tags from second XML file while merging two XML files
我可以借助XML :: Twig模块合并两个XML文件数据,但在某些情况下,在这种情况下,两个XML文件中都可能出现相同的标签,因此我需要保持第一个文件中的数据完整并删除从第二个开始。 有人可以让我知道如何通过XML::Twig
实现它吗?
下面是我用来合并两个XML数据的代码
第一个XML数据
<config>
<tag1>A1</tag1>
<tag2>A2</tag2>
</config>
第二个XML数据
<config>
<tag2>A2</tag2>
<tag3>A1</tag3>
<opt>
<user login="grep" fullname="BOB" />
<user login="stty" fullname="TOM" />
</opt>
</config>
<tag2>
数据出现在两个文件中。 我需要从第二个文件中删除重复的数据。
码
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;
}
该解决方案通过将所有第一级元素的标签名称添加到哈希%tags
。 在处理第二个文件时,如果哈希中还没有其标签名,则将每个第一级元素剪切并粘贴到原始文档中
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;
产量
<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.