私は初めて Python と minidom を使用しており、次のような要素から値を取得したいと考えています。
<test>value</test>
これは問題なく簡単ですが、値が空であるか、要素が存在しない場合は、デフォルトにフォールバックしたいと考えています。Python でこれを行う簡単な方法が見つからなかったため、最終的に次の関数を作成しました。
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
これを呼び出すには、次のようなものを使用します。
test = getXmlValue(node.getElementsByTagName('test'), '666')
これは機能し、問題なく動作しているように見えますが、それほど効率的でもエレガントでもないようです。
これを行うためのより良い方法はありますか、それとも何か問題がありますか?