ElementTree Help With DTD

Heston James - Cold Beans heston.james at coldbeans.co.uk
Tue Sep 30 09:43:59 EDT 2008


Afternoon All,

 

I have used elementtree for a little while now parsing simple XML documents
and found it pretty intuitive. Today is the first time I've used the library
to create an XML file though.

 

I have a simple script which looks like this:

 

                # Save the configuration to the XML file.

                # Create the root element,

                top = etree.Element("top")

                

                # Create the other elements in the tree.

                sub1 = etree.SubElement(top, "sub1")

                sub1.text = "other text"

                

                # Create the core element tree object.

                tree = etree.ElementTree(top)

                # Write the XML to the file system.

                tree.write("/path/to/my.xml")

 

This works just fine, in as much that I get an XML file with the correct XML
content within it, like so:

 

<top>

      <sub1>other text</sub1>

</top>

 

However, I really need to validate this built XML against a DTD schema that
I have, and also add the DTD reference to the top of the generated file, so
other applications parsing it in can validate it properly, like so:

 

<?xml version="1.0" encoding="iso-8859-1"?>

<!DOCTYPE top SYSTEM "top.dtd">

<top>

      <sub1>other text</sub1>

</top>

 

As you can see, this also includes the proper XML definition for the file.

 

Can anyone offer any pointers on how to have ElementTree add these
additional definitions to the file it generates? And also validate itself
against the DTD before writing to the FS?

 

Many thanks guys, I really appreciate it.

 

Heston

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/d0ff63aa/attachment.html>


More information about the Python-list mailing list