![](/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.