XPath expressions select nodes relative to a context. Common patterns:
/library/book -- all <book> children of the root <library>
//book -- all <book> elements anywhere in the document
//book[1] -- the first <book> element (XPath is 1-indexed)
//book[@id="2"] -- <book> element with id attribute equal to "2"
//book/title/text() -- the text content of all <title> elements
//book[year > 2022] -- books where <year> is greater than 2022
count(//book) -- count all <book> elements
Test XPath expressions from the command line with xmllint:
xmllint --xpath "//book/title/text()" library.xml
xmllint --xpath "count(//book)" library.xml
Use XPath in Python with the lxml library:
from lxml import etree
tree = etree.parse("library.xml")
root = tree.getroot()
# Select all book titles
titles = root.xpath("//book/title/text()")
for t in titles:
print(t)
# Select books published after 2022
recent = root.xpath("//book[year > 2022]")
for book in recent:
print(book.find("title").text)