How to use XPath in Python?

Sometimes, we want to use XPath in Python.

In this article, we’ll look at how to use XPath in Python.

How to use XPath in Python?

To use XPath in Python, we can use the xml.etree.ElementTree class.

For instance, we write

import xml.etree.ElementTree as ET
root = ET.parse(filename)
result = ''

for elem in root.findall('.//child/grandchild'):
    if elem.attrib.get('name') == 'foo':
        result = elem.text
        break

to parse the XML file at the filename path with parse.

And then we call root.findall with an XPath to the elements we want.

Then we loop through the returned elements with a for loop.

In the loop we use attrib.get to get the attribute values by its name.

And we get the text content of the element with text.

Conclusion

To use XPath in Python, we can use the xml.etree.ElementTree class.