XML Viewer, Formatter & Validator · Tutorial
How to select XML elements with XPath
8 min readbeginnerUpdated
You need to pull specific values out of XML, for a test, an integration or a report. You will write XPath expressions step by step on a book catalogue and see what each returns.
What you need
- The XML Formatter, on its XPath tab
Steps
Select all elements of a name
Load the example and type
//book. The double slash means “anywhere in the document”. Three book elements match.Read attributes
//book/@idreturns the id attribute of each book. The @ marks an attribute.Filter by a value
Square brackets filter.
//book[price > 25]/titlereturns titles of books priced above 25, and//book[@format="ebook"]returns the ebook.//book[price > 25]/title //book[@format = "ebook"]/author //book[contains(title, "XML")]Count and combine
Functions compute values:
count(//book)gives 3, andstring-join(//author, "; ")joins all authors into one string.Use the path shown
Each result shows where it is, such as
/catalog/book[2]/title. Use positions likebook[2]only when order really matters.
Try it yourself
Opens the XML Viewer, Formatter & Validator with this tutorial's sample loaded.
Common mistakes
- Case differences
//Bookand//bookare different. Copy names exactly from the XML.- Comparing text with numbers
price > 25compares numbers. If values contain currency symbols, usenumber(translate(price, "€", "")).
Next steps
Go back to the XML Viewer, Formatter & Validator, or keep going with one of these:
FAQ
What is the difference between / and //?
A single slash steps to a direct child; a double slash searches all descendants. /catalog/book and //book return the same books here, but // is slower on very large documents.