How to add single line comment or multiline comment using tcl tdom?
For example
<book>
<!-- book 1 price -->
<name> abc </name>
<price> 150 </price>
</book>
It depends on what you are doing. You can add comments by creating comment nodes and inserting it into the DOM tree, or by inserting from a list descriptor, or by inserting from a script.
package require tdom
set doc [dom createDocument book]
set root [$doc documentElement]
$root appendChild [$doc createComment "book 1 price"]
If you already have a document and just want to add a comment at the top, you can do this:
set doc [dom parse ...]
set root [$doc documentElement]
$root insertBefore [$doc createComment "book 1 price"] [$root firstChild]
If you don't have a document and need to create the name
and price
elements as well, creating nodes one by one becomes too tedious. Instead one can do this:
set doc [dom createDocument book]
set root [$doc documentElement]
$root appendFromList {#comment "book 1 price"}
$root appendFromList {name {} {{#text abc}}}
$root appendFromList {price {} {{#text 150}}}
If you want to populate a document from a data structure and possibly add some logic, you'll probably want to use appendFromScript
, which means you need to define some node commands first.
dom createNodeCmd element book
dom createNodeCmd element name
dom createNodeCmd element a
dom createNodeCmd element price
dom createNodeCmd comment c
dom createNodeCmd text t
set doc [dom createDocument books]
set root [$doc documentElement]
set n 0
foreach {nm pr} {
abc 150
def 120
ghi 200
} {
incr n
$root appendFromScript {book id $n {
c "book $n price"
name {a href "http://what/ever?book=$n" {t $nm}}
price {t $pr}
}}
}
(Note: in the documentation, the type argument to createNodeCmd
is supposed to be elementNode
, commentNode
, textNode
, etc. IME it can be abbreviated to one or two letters, e.g. e
/ t
/ co
. Leaving out the Node
part seems to be a legible compromise.)