Tcl- How to generate xml using xmlgen
This is a short tutorial on Tcl. To generate xml you will need TclLXML library for Tcl. You can simply install it using
Debian/Ubuntu(use sudo):
1 | apt-get install tclxml |
Fedora/Redhat:
1 | yum install tclxml |
However, you still need to install xmlgen. You can find it from here. I used version 1.4. The latest version until this is written was written in 2002. You will find instruction on how to install it in README file. If you don’t know where to install, I will suggest you to change the prefix to /home/$USER/ and move the lib directory to the place where TclXML is installed.
In your tcl file, you will have to import the library package (xmlgen). To make life easier, you can use xmlgen namespace as well. Following is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package require xmlgen namespace import ::xmlgen::* #Declare all the elements here declaretag foo declaretag bar foo att1=value1 att2=value2 ! { bar att3=value3 ! { valueofbar1} bar- valueofbar2 valueoffoo1 } |
This will generate the following:
1 2 3 | valueofbar1 valueofbar2 valueoffoo1 |
Now the problem is how you can print this in a file? You will need to use channel proc. In the documentation it was not quite clear what would be body. In the previous example the part from foo in the tcl code till end of it’s curly bracket is the body. See the following example:
1 2 3 | set fileId [open "some/file/is/here.not", w] channel $fileId { body } |
Here, body can spreaded into few lines. That is fine. You don’t have to use -nonewline in the example above as it is taken care of in the library. However, if you want to add xml version and other information (xmlns or xslt information), you will need to write them manually before you start writing the xml body.
If you have more question feel free to ask here, I will add them to this article.

27. October 2009 at 4:05 pm :
I am new to TCL and wanted to create a XML file using TCL scripts. I had installed xmlgen and works just fine. But now I need the results in a file. I had also tried your example of the channel proc but I believe I don’t understand how it works.
set fileId [open "some/file/is/here.not", w]
channel $fileId { body }
Would you please give me another example or the actual code?
Thanks!
Kash