4️⃣ 🧭 XPath Tutorial
Estimated reading: 4 minutes 25 views

💡 XPath Examples – Practical Queries for Real-World XML Data

🧲 Introduction – Why Learn XPath Examples?

Theory alone can’t teach XPath. To truly master XPath, you need to see it in action—navigating real XML structures, applying filters, selecting nodes, and extracting values. These XPath examples cover everything from basic selection to advanced conditions using axes, operators, and functions.

🎯 In this guide, you’ll learn:

  • Common XPath query patterns
  • Real-world use cases for selecting elements, attributes, and text
  • Combined usage of predicates, operators, and functions
  • Copy-ready code examples for your projects

📄 Sample XML

<library>
  <book id="101" category="programming">
    <title lang="en">XPath Basics</title>
    <author>Jane Doe</author>
    <price>499</price>
  </book>
  <book id="102" category="reference">
    <title lang="en">Advanced XPath</title>
    <author>John Smith</author>
    <price>599</price>
  </book>
  <book id="103" category="fiction">
    <title lang="fr">XPath pour les nuls</title>
    <author>Jean Dupont</author>
    <price>399</price>
  </book>
</library>

🧾 Basic XPath Selection Examples

XPath ExpressionResult
/library/bookAll <book> elements under <library>
//titleAll <title> elements
//book[@id='101']<book> with id="101"
//book[1]First <book> element
//book[last()]Last <book> element

🧭 Attribute and Text Selection

//book/@id

✅ Selects all id attribute values from <book> elements.

//book/title/text()

✅ Gets the text content of all <title> nodes.

//title[@lang='fr']

✅ Selects <title> where lang="fr"


🎯 Conditional Queries with Operators

//book[price > 500]

✅ Books priced above 500.

//book[author='Jane Doe']

✅ Books authored by Jane Doe.

//book[@category='fiction' and price < 500]

✅ Fiction books that cost less than 500.


🔁 XPath with Functions

//title[contains(text(),'XPath')]

✅ Selects titles that contain the word “XPath”.

//author[starts-with(text(),'John')]

✅ Authors whose name starts with “John”.

//book[position() < 3]

✅ First two books.


🔀 XPath Axes in Use

//title/parent::book

✅ Gets the <book> node that is the parent of <title>.

//book/child::price

✅ Selects <price> children of <book>.

//book/following-sibling::book

✅ Gets all <book> nodes that follow another <book>.


🧪 Complex Queries

//book[price < 600 and @category='programming']/title

✅ Titles of programming books priced under 600.

//book[author='Jean Dupont']/title[@lang='fr']

✅ French titles authored by Jean Dupont.

//book[author and price > 400]

✅ Books that have both an <author> and a price above 400.


🧰 XPath in JavaScript Example

var result = document.evaluate("//book[price > 500]/title/text()", xmlDoc, null, XPathResult.ANY_TYPE, null);
var node = result.iterateNext();
while (node) {
  console.log(node.nodeValue); // Outputs matching titles
  node = result.iterateNext();
}

✅ Evaluate XPath expressions in JavaScript for real-time XML interaction.


✅ Best Practices for XPath Queries

  • ✔️ Use predicates ([ ]) to narrow down node selections
  • ✔️ Use functions like contains() and starts-with() for flexible matching
  • ✔️ Use axes for complex structural relationships
  • ✔️ Test expressions with XML tools like XMLSpy, XPath Tester, or browser DevTools
  • ❌ Don’t over-nest expressions—use // and logical operators to simplify

📌 Summary – Recap & Next Steps

These XPath examples show how powerful and expressive the language can be. Whether you’re filtering by attributes, content, structure, or relationships, XPath gives you full control over XML traversal and selection.

🔍 Key Takeaways:

  • Use /, //, @, text(), and [] to build flexible queries
  • Combine logic with and, or, not() for smart filters
  • Apply functions like contains() and last() for dynamic queries
  • Use in JavaScript, Python, Java, PHP, and more for real-time XML processing

⚙️ Real-world relevance: XPath is used in web scraping, XSLT, XML databases, configuration loaders, and validation systems.


❓ FAQs – XPath Examples

❓ How do I get the second book element?
✅ Use //book[2].

❓ How do I find a node that contains specific text?
✅ Use contains(text(),'your text').

❓ Can XPath match both tag and attribute values?
✅ Yes, combine them like //book[@id='101' and author='Jane'].

❓ Is XPath zero-based or one-based?
✅ XPath uses 1-based indexing (i.e., [1] is the first node).

❓ Can I use XPath in JavaScript?
✅ Yes. Use document.evaluate() with XML or HTML documents.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

XPath Examples

Or Copy Link

CONTENTS
Scroll to Top