2013-11-04 29 views
1

我想简单地添加的XML代码(从parsed_balance_chunk)块,测试尝试添加一个孩子,作为兄弟的影响。我玩弄王氏都“insertAfter” &“addSibling”和测试如何插入XML中的不同部分的片段。通过“insertAfter”(以及“insertBefore”),它将它添加为“C”的最后一个孩子。 1.)我怎样才能让它插入“C”的第一个孩子(即在“D”之前)? 2.)通过另一项测试,我怎样才能让它成为“C”的兄弟姐妹?当我尝试“addSibling”时,它会回传一条消息,说'添加文档片段,但尚未支持addSibling!'。的Perl的libxml - InsertAfter/addSibling

而且,与$ FRAG的定义,如果我把它定义在foreach望向窗外,只增加了$ 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> 
+0

对不起,我我不确定你的提问。我之所以添加一个片段是因为我需要插入一大块xml节,而'parsed_balance-chunk'符合法案。 – CraigP

回答

1

从文档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. 

...所以,如果你想插入作为新的第一个孩子,你需要获得当前的第一个子节点上的手柄,像这样:

$node->insertBefore($frag, $node->firstChild); 
+0

设置$ ref为$ node-> firstChild工作!我不确定为什么我不能明确地设置$ ref(例如'D')。谢谢! – CraigP

+0

因为'D'不是节点。这只是一封信。 – ikegami

1
#1 
$node->insertBefore($frag, $node->firstChild); 
#2 
$node->parentNode->insertAfter($frag, $node);