Inserting DTD statement to XML

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Mar 20 02:31:28 CET 2008


En Wed, 19 Mar 2008 15:33:19 -0300, jakecjacobson at gmail.com  
<jakecjacobson at gmail.com> 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"?>
> <!DOCTYPE employees PUBLIC "-//ICES//DTD ICES EMPLOYEES//EN" "">
> <employees>
>    ...
> </employees>
>

Try this:

 from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
dt = impl.createDocumentType("employees", "-//ICES//DTD ICES  
EMPLOYEES//EN", "")
doc = impl.createDocument(None, "employees", dt)
root = doc.documentElement
node = doc.createElement("foo")
node.setAttribute("some","attribute")
node.setAttribute("attr","value")
root.appendChild(node)
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 http://codespeak.net/lxml

import xml.etree.ElementTree as ET
root = ET.Element("employees")
ET.SubElement(root, "foo", some="attribute", attr="value")
ET.dump(root)
# <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"  
"">\n')
f.write(ET.tostring(root))
f.close()

(note: the lxml version may have doctype support)

-- 
Gabriel Genellina




More information about the Python-list mailing list