gpt4 book ai didi

Perl:使用 XML::Twig 插入 XML::Twig 节点

转载 作者:行者123 更新时间:2023-12-01 16:20:21 24 4
gpt4 key购买 nike

我正在比较两个 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>

最佳答案

您可能应该移动节点(我不记得当您尝试插入一个已经是树的一部分的元素时会发生什么)。所以写 $newXCRmo->move(first_child($currentBuilds)) 看看这是否会改善这种情况。

我没有太多时间看你的代码,所以它可能还有其他问题。

关于Perl:使用 XML::Twig 插入 XML::Twig 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38503943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com