Learn to Code via Tutorials on Repl.it!

← Back to all posts
Searching xml in Python 2.7
franciscoareasareas (7)

Searching an xml in Python

Starting with version 2.7 ElementTree has a better support for XPath queries. XPath is a syntax to enable you to navigate through an xml like SQL is used to search through a database. Both find and findall functions support XPath. The xml below will be used for this example

XPath queries are built as if it were a path to the file you want. They separate tags with / and xml attributes are accessed with an @ before the attribute name.
Specifically for ElementTree, you don't specify the full path, just the relative path based on the object you're using.

Searching for all books:

Searching for the book with title = ‘The Colour of Magic’:

Searching for the book with id = 5:

Search for the second book:

Search for the last book:

Search for all authors:

timmy_i_chen (1200)

Neat! Concise and informative. Thanks!

franciscoareasareas (7)

@timmy_i_chen Thanks. I found it really powerful to navigate through xml. I had written it for Stackoverflow documentation and saved it when they shutdown the site.