Inserting DTD statement to XML

J

jakecjacobson

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>
 
G

Gabriel Genellina

En Wed, 19 Mar 2008 15:33:19 -0300, (e-mail address removed)
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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top