Skip to content Skip to sidebar Skip to footer

Python Xml - Search For Attribute With Regular Expressions

In my xml file, I have nodes like this: I know how to use .findall to search for attributes but now, it looks like I would need t

Solution 1:

Unfortunately, things like contains() and starts-with() are not supported by xml.etree.ElementTree built-in library. You can manually check the attribute, finding all waitingJobs and using .attrib to get to the idList value:

import xml.etree.ElementTree as ET

data = """<jobs>
    <waitingJobs idList="J03ac2db8 J03ac2fb0"/>
</jobs>
"""

root = ET.fromstring(data)
value = 'J03ac2db8'print([elm for elm in root.findall(".//waitingJobs[@idList]") 
       if value in elm.attrib["idList"]])

With lxml.etree, you can use xpath() method and contains() function:

import lxml.etree as ET

data = """<jobs>
    <waitingJobs idList="J03ac2db8 J03ac2fb0"/>
</jobs>
"""

root = ET.fromstring(data)

value = 'J03ac2db8'print(root.xpath(".//waitingJobs[contains(@idList, '%s')]" % value))

Post a Comment for "Python Xml - Search For Attribute With Regular Expressions"