Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a DTD using minidom in python

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">
<foo/>
like image 769
ashchristopher Avatar asked Feb 25 '10 20:02

ashchristopher


People also ask

What is Minidom in Python?

minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller.

Is there a DOM in Python?

The DOM is a standard tree representation for XML data. The Document Object Model is being defined by the W3C in stages, or “levels” in their terminology. The Python mapping of the API is substantially based on the DOM Level 2 recommendation. DOM applications typically start by parsing some XML into a DOM.

What is Toprettyxml?

toprettyxml. n.toprettyxml(indent='\t',newl='\n') Returns a string, plain or Unicode, with the XML source for the subtree rooted at n, using indent to indent nested tags and newl to end lines. toxml. n.toxml( )


1 Answers

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\'><foo/>

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.

like image 147
Amos Newcombe Avatar answered Sep 18 '22 10:09

Amos Newcombe