我正在尝试简单地添加一段xml代码(来自parsed_balance_chunk),测试尝试添加子对象和兄弟对象的效果。我同时使用了“xml”和"addSibling“,并测试如何在insertAfter的不同部分中插入片段。对于"insertAfter“(就这一点而言,"insertBefore"),它将其添加为"C”的最后一个子项。1.)如何将其作为"C“的第一个子项插入(即在”D“之前)?2.通过另一个测试,我如何才能使它成为"C“的兄弟?当我尝试" addSibling“时,它会弹出一条消息:”使用尚不支持的addSibling添加文档片段!“。
此外,对于$frag的定义,如果我在foreach look之外定义它,它只会将$frag添加到第一个节点(而不是第二个出现“C”的节点)。
代码:
use warnings;
use strict;
use XML::LibXML;
use Data::Dumper;
my $parser = XML::LibXML->new({keep_blanks=>(0)});
my $dom = $parser->load_xml(location => 'test_in.xml') or die;
my @nodes = $dom->findnodes('//E/../..');
foreach my $node (@nodes)
{
my $frag = $parser->parse_balanced_chunk ("<YY>yyy</YY><ZZ>zz</ZZ>");
$node->insertBefore($frag, undef);
#$node->addSibling($frag);
}
open my $FH, '>', 'test_out.xml';
print {$FH} $dom->toString(1);
close ($FH);输入文件:
<?xml version="1.0"?>
<TT>
<A>ZAB</A>
<B>ZBW</B>
<C>
<D>
<E>ZSE</E>
<F>ZLC</F>
</D>
</C>
<C>
<D>
<E>one</E>
</D>
</C>
</TT>输出文件:
<?xml version="1.0"?>
<TT>
<A>ZAB</A>
<B>ZBW</B>
<C>
<D>
<E>ZSE</E>
<F>ZLC</F>
</D>
<YY>yyy</YY>
<ZZ>zz</ZZ>
</C>
<C>
<D>
<E>one</E>
</D>
<YY>yyy</YY>
<ZZ>zz</ZZ>
</C>
</TT>发布于 2013-11-05 05:00:21
来自XML::LibXML::Node->insertNode($newNode, $refNode)的文档
The method inserts $newNode before $refNode. If $refNode is
undefined, the newNode will be set as the new last child of the
parent node. This function differs from the DOM L2 specification,
in the case, if the new node is not part of the document, the node
will be imported first, automatically....so,如果希望将其作为新的第一个子节点插入,则需要获取当前第一个子节点的句柄,如下所示:
$node->insertBefore($frag, $node->firstChild);发布于 2013-11-05 05:05:09
#1
$node->insertBefore($frag, $node->firstChild);
#2
$node->parentNode->insertAfter($frag, $node);https://stackoverflow.com/questions/19776713
复制相似问题