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?