2011-05-07 92 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

相关问题