3

Minimal DOM (minidom) is not allowing for the setting of attributes on the root element.

Here is my code:

    # -*- coding: utf-8 -*- 

    from xml.dom import minidom
    import os

    root = minidom.Document()

    xml = root.createElement('dbtable')
    root.setAttribute("name", 'states')
    root.appendChild(xml)

Here is the error:

Traceback (most recent call last):
  File "C:\Users\sbing\.qgis2\python\plugins\SaveAttributesXML\createXML01.py", line 11, in <module>
    root.setAttribute( "id", 'myIdvalue' )
AttributeError: Document instance has no attribute 'setAttribute'
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Scott Bing
  • 125
  • 4
  • 14

1 Answers1

2

You are trying to set an attribute for the document itself, not to the root element.

When you invoke Document(), you simply create Information about the declarations needed to process a document. In no way it creates a root element: Maybe with code you will understand better:

>>> from xml.dom import minidom
>>> xmldoc = minidom.Document()
>>> xmldoc.toxml()
'<?xml version="1.0" ?>'
>>> xmldoc.childNodes
[]

What this piece of code tell us? It simply says when you invoke Document(), you basically create the XML prolog and nothing else. An other proof of this is that when we call childNodes, we get an empty NodeList list object.

But now that you created the XML document object, you are read to add whatever data you want as long as you respect the XML DOM specification. And in this, you are right: the first thing we have to do is to create the root element, so let us do it:

>>> root_element = xmldoc.createElement('root')
>>> root_element.setAttribute('id', 'id1')

The two lines above create a DOM element we called root and set an attribute we call id with the value id1. But for the moment this does not affect our XML document object at all:

>>> xmldoc.toxml()
'<?xml version="1.0" ?>'

To attach root_element we do it as we do for any other normal element:

>>> xmldoc.appendChild(root_element)
<DOM Element: root at 0x7f0d654a5bd8>

As you can see, we have now a root element called root and attached to the XML document object we created previously:

>>> xmldoc.toxml()
'<?xml version="1.0" ?><root id="id1"/>'

But now you may say: what makes you think root_element is considered as the root element and not just as a usual one?

Well: that was the first element we attached to the XML document, so by default, minidom is smart enough to consider it as the root element where everything else from now on will be wrapped:

>>> xmldoc.documentElement
<DOM Element: root at 0x7f0d654a5bd8>
>>> xmldoc.documentElement.tagName
'root'

Hope this is clear, if not then do not hesitate to ask through comments.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130