xml.dom.minidom - documentElement vs. childNodes

Skip Montanaro skip at pobox.com
Mon Aug 30 23:31:19 CEST 2004


In response to:

    >> I'm getting somewhat painfully acquainted with xml.dom.minidom.  What
    >> is the relationship between its documentElement attribute and its
    >> childNodes list?  I thought XML documents consisted of a single,
    >> possibly compound, node.  Why is a list of childNodes needed?

Peter provided this interpreter session:

    >>> import xml.dom.minidom as md
    >>> dom = md.parseString("""<?xml version="1.0" ?><!--comment--><root/>""")
    >>> dom.childNodes
    [<DOM Comment node "comment">, <DOM Element: root at 0x4038c1ac>]

So a document can have multiple nodes.  It appears they can only have a
single Element node though:

    >>> dom = md.parseString("""<?xml version="1.0" ?><!--comment--><root/><root2/>""")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "/Users/skip/local/lib/python2.4/xml/dom/minidom.py", line 1925, in parseString
        return expatbuilder.parseString(string)
      File "/Users/skip/local/lib/python2.4/xml/dom/expatbuilder.py", line 940, in parseString
        return builder.parseString(string)
      File "/Users/skip/local/lib/python2.4/xml/dom/expatbuilder.py", line 223, in parseString
        parser.Parse(string, True)
    ExpatError: junk after document element: line 1, column 43
    ...

I guess the documentElement attribute of the dom refers to that lone Element
node.

Thanks,

Skip



More information about the Python-list mailing list