2013-11-04 31 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);