Pqp239 Pqp239 - 2 years ago 382
Python Question

xml.etree.ElementTree findall

I am parsing an XML file using xml.etree.ElementTree. I want to find elements based off the name attribute.

fnd = root.findall("./player[@name='Pqp239']")

But, this only will find exact matches for the name. How would you go about finding elements whose name contains a part of a name? So it would be something like this

fnd = root.findall("./player[@name='rob']")

would find all elemnts whose name contain rob like these:


Answer Source

You can use the contains() function, but this would only work if you would switch to lxml.etree instead of xml.etree.ElementTree which has only partial/limited XPath support:

import lxml.etree as ET

tree = ET.parse("input.xml")
root = tree.getroot()

root.xpath("./player[contains(@name, 'rob')]")

Note though, that to make the partial match case-insensitive you would need to additionally apply the translate() function:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download