Skip to content Skip to sidebar Skip to footer

How To Create "virtual Root" With Python's Elementtree?

I am trying to use Python's ElementTree to generate an XHTML file. However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a

Solution 1:

I don't know if there's a better way but I've seen this done:

Create the base document as a string:

<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html></html>

Then parse that string to start your new document.

Solution 2:

I have had the same problem. When parsing a document and writing the docuemnt back again the doc-type definition is not present anymore. I found a solution browsing the documentation:

link text

Saving HTML Files #

To save a plain HTML file, just write out the tree.

tree.write("outfile.htm")

This works well, as long as the file doesn’t contain any embedded SCRIPT or STYLE tags.

If you want, you can add a DTD reference to the beginning of the file:

file = open("outfile.htm", "wb")
file.write(DTD + "\n")
tree.write(file)
file.close()

Post a Comment for "How To Create "virtual Root" With Python's Elementtree?"