create a XML file with DOM

Peter Hansen peter at engcorp.com
Mon Oct 25 19:02:50 EDT 2004


Juliano Freitas wrote:
> i'm usin a DOM module to process a xml file. I'm having problems with
> the appenChild function. Why in my example below i can't append the
> child 'ele' into the swdb.

Does the following exploration help you?  Note the difference between
what is output by root.toprettyxml() and root.firstChild.toprettyxml().
You need to go back to the XML specification and read up a little
bit about the difference between the "root" and the "document element".

c:\>python
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> from xml.dom import *
 >>> xmldoc = getDOMImplementation()
 >>> print xmldoc
<xml.dom.minidom.DOMImplementation instance at 0x00A0E288>
 >>> root = xmldoc.createDocument('', 'swdb', '')
 >>> root.firstChild
<DOM Element: swdb at 0x9e99e0>
 >>> root
<xml.dom.minidom.Document instance at 0x009DFF80>
 >>> ele = root.createElement('visualinfo')
 >>> root
<xml.dom.minidom.Document instance at 0x009DFF80>
 >>> root.appendChild(ele)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "c:\a\python23\lib\xml\dom\minidom.py", line 1552, in appendChild
     raise xml.dom.HierarchyRequestErr(
xml.dom.HierarchyRequestErr: two document elements disallowed
 >>> root.toprettyxml()
'<?xml version="1.0" ?>\n<swdb/>\n'
 >>> root.firstChild.toprettyxml()
'<swdb/>\n'
 >>> root.firstChild.appendChild(ele)
<DOM Element: visualinfo at 0x9ed5a8>
 >>> root.firstChild.toprettyxml()
'<swdb>\n\t<visualinfo/>\n</swdb>\n'
 >>> root.toprettyxml()
'<?xml version="1.0" ?>\n<swdb>\n\t<visualinfo/>\n</swdb>\n'


-Peter



More information about the Python-list mailing list