Pqp239 Pqp239 - 6 months ago 77
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:

Rob
Robert
chifforobe

Answer

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: