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

Steps

  1. Select all elements of a name

    Load the example and type //book. The double slash means “anywhere in the document”. Three book elements match.

  2. Read attributes

    //book/@id returns the id attribute of each book. The @ marks an attribute.

  3. Filter by a value

    Square brackets filter. //book[price > 25]/title returns 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")]
  4. Count and combine

    Functions compute values: count(//book) gives 3, and string-join(//author, "; ") joins all authors into one string.

  5. Use the path shown

    Each result shows where it is, such as /catalog/book[2]/title. Use positions like book[2] only when order really matters.

Try it yourself

Opens the XML Viewer, Formatter & Validator with this tutorial's sample loaded.

Try it now

Common mistakes

Case differences
//Book and //book are different. Copy names exactly from the XML.
Comparing text with numbers
price > 25 compares numbers. If values contain currency symbols, use number(translate(price, "€", "")).

Next steps

Go back to the XML Viewer, Formatter & Validator, or keep going with one of these:

Tutorial · 6 min · beginner

How to find and fix errors in invalid XML

Use the XML formatter's live check to locate an unclosed tag and an unescaped ampersand, fix them one by one, and confirm the document is well-formed.

Tutorial · 5 min · beginner

How to make XML from an API readable

Turn a one-line XML response into indented, readable XML, find the values you need, and keep the content exactly as it was.

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.