minidom sample code

Bengt Richter bokr at oz.net
Mon Sep 8 19:27:46 EDT 2003


On 8 Sep 2003 13:51:06 -0700, mirandacascade at yahoo.com (Miranda Evans) wrote:

>Seeking sample python script that makes use of of xml.dom.minidom. 
>Specifically, would like to see code where xml.dom.minidom is used to
>create an output file the contents of which is an XML document.
>
>Ideally, the output file would a simple XML document such as the one
>below.
>
><?xml version="1.0" ?> 
><TrivialRootTag>TrivialContents</TrivialRootTag>
>
>Workstation O/S is Win2K; version of Python is 2.2.
>
>Can anyone point me to a documentation/link/whatever that provides
>such sample code?  Thank you.

Did you look at the xml.dom.minidom docs at

    http://www.python.org/doc/current/lib/module-xml.dom.minidom.html

Taken from the first page verbatim:

 >>> from xml.dom.minidom import getDOMImplementation
 >>> impl = getDOMImplementation()
 >>> newdoc = impl.createDocument(None, "some_tag", None)
 >>> top_element = newdoc.documentElement
 >>> text = newdoc.createTextNode('Some textual content.')
 >>> top_element.appendChild(text)
 <DOM Text node "Some textu...">

Using the methods described on the second page:

 >>> newdoc.toxml()
 '<?xml version="1.0" ?>\n<some_tag>Some textual content.</some_tag>'

or:

 >>> newdoc.toprettyxml()
 '<?xml version="1.0" ?>\n<some_tag>\n\tSome textual content.\n</some_tag>\n'

and showing what that looks like printed:

 >>> print newdoc.toprettyxml()
 <?xml version="1.0" ?>
 <some_tag>
        Some textual content.
 </some_tag>

I'll leave it to you to change the spelling to match your example ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list