Case Insensitive Search in Python ElementTree

I need to parse an XML that has tag names that can be anyway (mixed, top, bottom, etc.), and I don't know what comes first. How to force findall to completely exclude case in ElementTree?

   # Does not work
   variables = message.findall("VaRiAbLE")
+5
source share
2 answers

You just get a string from a tree, a lower case letter, and redo the tree. Then it should be analyzed

import xml.etree.ElementTree as ET
def to_parseable(tree):
    t = ET.tostring(tree)
    t = t.lower()
    return ET.fromstring(t)
+5
source

Regex to the rescue. Note that this is probably terrible in terms of performance, but great for retrieved XML attributes from elements.

def getInsensitiveAttrbiute(element, key) :

   keyRegex = re.compile(key, re.IGNORECASE)
   for key in element.attrib.keys() :
       if keyRegex.match(key) :
           return element.attrib[key]
   raise KeyError


element = ET.fromstring('<FOO src="BAR" />')
print getInsensitiveAttrbiute(element, "sRc")
+1
source

All Articles