【发布时间】:2016-07-21 21:58:29
【问题描述】:
我正在比较两个 XML 文件。如果我发现其中一个文件中缺少一个节点,我想将它插入到另一个文件中。这是我一直在尝试的方法:
my $out_file = 'fbCI_report.xml';
open my $fh_out, '>>', $out_file or die "Can't open $out_file for writing: $!";
my $currentReport = XML::Twig->new( pretty_print => 'indented' );
$currentReport->parsefile($path_to_currentReport);
print "Loaded current report.\n";
my $newReport = XML::Twig->new( pretty_print => 'indented' );
$newReport->parsefile($path_to_newReport);
print "Loaded new report.\n";
my $currentRoot = $currentReport->root; # get the root
my $currentBuilds = $currentRoot->first_child(); # get the builds node
my $currentXCR = $currentBuilds->first_child(); # get the xcr node
my $newRoot = $newReport->root; # get the root
my $newBuilds = $newRoot->first_child(); # get the builds node
my $newXCR = $newBuilds->first_child(); # get the xcr node
my @currentXCRarray = $currentBuilds->children('xcr');
my @newXCRarray = $newBuilds->children('xcr');
my $numberOfxcr = $newBuilds->children_count();
foreach my $currentXCRmod ( @currentXCRarray ) {
my $currentID = $currentXCRmod->att("id");
foreach my $newXCRmod (@newXCRarray) {
my $newID = $newXCRmod->att("id");
if ( $newID == $currentID ) {
last;
}
elsif ( $count == $numberOfxcr && $newID != $currentID ) {
my $insert = $currentBuilds->insert_new_elt($newXCRmod);
print "XCR does not exist in current report, adding it..\n";
}
$count++;
}
}
print $fh_out $currentReport->sprint();
close $fh_out;
但是,这并没有插入具有相应子节点的节点,但我猜是对节点的引用:<XML::Twig::Elt=HASH(0x326efe0)/>。有没有办法正确插入节点?我还没有在 CPAN 网站上找到任何东西。
样本数据,current.xml:
<project>
<builds>
<xcr id="13367" buildable="false">
<artifact name="rb"/>
<artifact name="syca"/>
</xcr>
<xcr id="13826" buildable="false">
<artifact name="dcs"/>
</xcr>
<\builds>
<\project>
新的.xml:
<project>
<builds>
<xcr id="13367" buildable="false">
<artifact name="rb"/>
<artifact name="syca"/>
</xcr>
<xcr id="13826" buildable="false">
<artifact name="dcs"/>
</xcr>
<xcr id="10867" buildable="true">
<artifact name="smth"/>
<artifact name="top"/>
<artifact name="tree"/>
</xcr>
<\builds>
<\project>
【问题讨论】:
-
另外:示例输入/输出 XML 在这里会有所帮助!
-
我还建议不要只使用
first_child来遍历你的树,而是使用xpath明确地这样做。 -
那么对于这些 XML 示例,您是否希望基于
xcrid 进行合并? -
@Sobrique 是的,这正是我想在这里做的。我想知道为什么我从来没有想到这个词。