2

I am using Python and minidom for the first time and want to get a value from an element something like:

<test>value</test>

This is fine and straightforward, but if the value is empty or the element does not exist then I want to fall back to a default. I could find no simple way to do this in Python so I ended up writing the following function:

def getXmlValue(address, default):
   """Return XML node value if available, otherwise return a default"""

   # If the xml element is empty then we get an IndexError exception,
   # if the xml element is missing then the 'if' statement is false
   if address:
      try:
         return address[0].childNodes[0].nodeValue
      except IndexError:
         return default

   return default

To call this I use something like:

test = getXmlValue(node.getElementsByTagName('test'), '666')

This does the job and seems to work fine, but doesn't seem all that efficient or elegant.

Is there a better way to do this or is there anything wrong with this?

1
  • That looks to be a perfectly reasonable way of getting the value without an error.
    – X-Istence
    Jun 11, 2011 at 9:24

2 Answers 2

2

If you use ElementTree it should be much easier.

from xml.etree.ElementTree import ElementTree, fromstring

xml = '<test>value</test>'
root = fromstring(xml)
test = root.text or '666'
0

since childNodes is going to be an array, how about just doing a length check and deciding otherwise. in some of my code I have something like below. If the childNode.length > 0 then I assign a the childNode[0] data otherwise just an empty string.

                my_element = alertitem.getElementsByTagName('solution')[0]
                result.mydata= my_element.childNodes[0].data if my_element.childNodes.length > 0 else ''

to me, seems better than a try except.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.