views:

270

answers:

2

I am trying to include a reference to a DTD in my XML doc using minidom.

I am creating the document like:

doc = Document()
foo = doc.createElement('foo')
doc.appendChild(foo)
doc.toxml()

This gives me:

<?xml version="1.0" ?>
<foo/>

I need to get something like:

<?xml version="1.0" ?>
<!DOCTYPE something SYSTEM "http://www.path.to.my.dtd.com/my.dtd"&gt;
<foo/>
+1  A: 

According to the Python docs, there is no implementation of the DocumentType interface in the minidom.

smencer
+2  A: 

The documentation is out of date. Use the source, Luke. I do it something like this.

from xml.dom.minidom import DOMImplementation

imp = DOMImplementation()
doctype = imp.createDocumentType(
    qualifiedName='foo',
    publicId='', 
    systemId='http://www.path.to.my.dtd.com/my.dtd',
)
doc = imp.createDocument(None, 'foo', doctype)
doc.toxml()

This prints the following.

<?xml version="1.0" ?><!DOCTYPE foo  SYSTEM \'http://www.path.to.my.dtd.com/my.dtd\'&gt;&lt;foo/&gt;

Note how the root element is created automatically by createDocument(). Also, your 'something' has been changed to 'foo': the DTD needs to contain the root element name itself.

Amos Newcombe
Nice. Glad you found a solution!
smencer