Search code examples
pythonminidom

Is parsing XML really this ugly in python?


I have a very small XML file (22 lines) with 5 elements(?) and I only want one value out of it.

This is the only way I can get the value I have found without using regular expressions

from xml.dom.minidom import parse
float(parse(filePath).getElementsByTagName('InfoType')[0].getElementsByTagName('SpecificInfo')[0].firstChild.data)

I feel like I'm missing something. There has to be a more pythonic way to handle XML, right?


Solution

  • The ElementTree library is a lot more Pythonic than xml.dom.minidom. If I'm understanding your XML structure right, your code would look something like this using ElementTree:

    import xml.etree.ElementTree as ET
    tree = ET.parse(filePath)
    data = float(tree.find('InfoType/SpecificInfo')[0].text)
    

    That should be a lot cleaner than what you're currently doing.