Inserting DTD statement to XML

Gabriel Genellina gagsl-py2 at
Thu Mar 20 02:31:28 CET 2008

En Wed, 19 Mar 2008 15:33:19 -0300, jakecjacobson at  
<jakecjacobson at> escribió:

> I am new to Python and I am writing a script to build a XML document
> and post it to a website.  I have a working script but need to insert
> a DTD statement in my XML document and can't find out how to do this.
> I am using "from xml.dom.minidom import Document"
> Some code I am using is:
> 	doc = Document()
> 	rootNode = doc.createElement("employees")
> 	doc.appendChild(rootNode )
> I get the following when I print it out
> <?xml version="1.0" ?>
> <employees>
>    ...
> </employees>
>What I would like is to have something like:
> <?xml version="1.0" encoding="utf-8"?>
> <employees>
>    ...
> </employees>

Try this:

 from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
dt = impl.createDocumentType("employees", "-//ICES//DTD ICES  
doc = impl.createDocument(None, "employees", dt)
root = doc.documentElement
node = doc.createElement("foo")
print doc.toxml()

But unless you *have* to use DOM for some reason, better switch to  
another, more "pythonic" library. Like ElementTree or lxml (both implement  
the same interface); the former comes with Python 2.5, the later you can  
get from

import xml.etree.ElementTree as ET
root = ET.Element("employees")
ET.SubElement(root, "foo", some="attribute", attr="value")
# <employees><foo attr="value" some="attribute" /></employees>
# ElementTree cannot generate a doctype header, do it by hand
f = open("test.xml", "w")
f.write('<?xml version="1.0" encoding="utf-8"?>\n')
f.write('<!DOCTYPE employees PUBLIC "-//ICES//DTD ICES EMPLOYEES//EN"  

(note: the lxml version may have doctype support)

Gabriel Genellina

More information about the Python-list mailing list