2011-05-07 32 views
1

我有一個現有的具有更多節點數的XML文檔,我想插入一個新節點,但是在某個位置。如何使用TCL(TDom)在現有的xml文件中插入新節點

文件看起來像:

<root> 
    <a>...</a> 
    <c>...</c> 
    <e>...</e> 
</root> 

...可視爲XML標籤一.../A,C .../C,E .../E。 (格式化的問題)

新的節點應該插入按字母順序排列的節點之間,產生:

<root> 
    <> 
    new node 
    <> 
    <> 
    new node 
    <> 
    <> 
    <> 
    new node 

我如何使用XPath在TCL找到現有節點之前插入新的節點或之後。

由於XML文檔中的現有標籤是按字母順序排列的,我還想保留該順序。

目前我正在使用tdom包。

有沒有人有關於如何插入這樣一個節點的想法?

+0

我已經格式化了您的問題,以便內容正確顯示,但似乎是在討論如何生成非格式良好的XML文檔。我不知道這個原因,但是如果你編輯你的問題來添加你想要去的地方,這將非常有幫助。 (至少4個空格的縮進形成了一個字面部分。) – 2011-05-07 05:44:51

回答

0

我很確定Tcl wiki上的tdom的tutorial回答了您的所有問題。在wiki上還有一些關於Xpath的附加信息。

2

如果你有這一個文件,demo.xml

<root> 
    <a>123</a> 
    <c>345</c> 
    <e>567</e> 
</root> 

而且要到這個(模空白):

<root> 
    <a>123</a> 
    <b>234</b> 
    <c>345</c> 
    <d>456</d> 
    <e>567</e> 
</root> 

那麼這是腳本要做到這一點:

# Read the file into a DOM tree 
package require tdom 
set filename "demo.xml" 
set f [open $filename] 
set doc [dom parse [read $f]] 
close $f 

# Insert the nodes: 
set container [$doc selectNodes /root] 

set insertPoint [$container selectNodes a] 
set toAdd [$doc createElement b] 
$toAdd appendChild [$doc createTextNode "234"] 
$container insertAfter $insertPoint $toAdd 

set insertPoint [$container selectNodes c] 
set toAdd [$doc createElement d] 
$toAdd appendChild [$doc createTextNode "456"] 
$container insertAfter $insertPoint $toAdd 

# Write back out 
set f [open $filename w] 
puts $f [$doc asXML -indent 4] 
close $f 
+0

爲了清楚起見,我通常會將這些查找和插入序列結合到過程中。 – 2011-05-07 06:08:39

相關問題