I have an existing XML document with more number of nodes and I want to insert a new node, but at a certain position.
The document looks something like:
<root>
<a>...</a&开发者_开发技巧gt;
<c>...</c>
<e>...</e>
</root>
... can be considered as xml tags a.../a, c.../c, e.../e. (formatting issue)
The new nodes should be inserted in alphabetical order in between the nodes, resulting in:
<root>
<>
new node
<>
<>
new node
<>
<>
<>
new node
How can I use XPath in TCL to find the existing node and insert new node before or after it.
I also want to preserve the order, since the existing tags in XML document are in alphabetical order.
At present I am using tdom package.
Does anyone have an idea on how to insert such a node?
If you've got this in a file, demo.xml
:
<root>
<a>123</a>
<c>345</c>
<e>567</e>
</root>
And want to go to this (modulo whitespace):
<root>
<a>123</a>
<b>234</b>
<c>345</c>
<d>456</d>
<e>567</e>
</root>
Then this is the script to do it:
# 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
I'm pretty sure that the tutorial for tdom on the Tcl wiki answers all of your questions. There is some additional information on Xpath on the wiki as well.
精彩评论