XPath Preceding-Sibling Axis Tutorial 🎯

beginner
16 min

XPath Preceding-Sibling Axis Tutorial 🎯

Welcome to the XPath Preceding-Sibling Axis tutorial! In this guide, we'll explore how to navigate through XML documents using XPath and the Preceding-Sibling Axis. Let's dive in!

Understanding XPath and XML 📝

Before we dive into the Preceding-Sibling Axis, let's make sure we're on the same page with XPath and XML.

XML (Extensible Markup Language) is a markup language used to store and transport data. It looks similar to HTML, but it's more flexible and can be used to create custom tags.

XPath is a language for finding information in an XML document. It's like a GPS for XML - it helps you navigate through the document and find specific elements.

The Preceding-Sibling Axis 💡

The Preceding-Sibling Axis allows you to select all the elements that come immediately before the current element, and that share the same parent node.

Here's a simple XML example:

xml
<parent> <sibling1>Sibling 1</sibling1> <current>Current Element</current> <sibling2>Sibling 2</sibling2> </parent>

In this example, sibling1 and sibling2 are the preceding siblings of current.

Accessing Preceding Siblings using XPath ✅

To select the preceding siblings using XPath, you can use the preceding-sibling function. The syntax is as follows:

xpath
./preceding-sibling::nodeName

In our example, if we want to select sibling1, the XPath expression would be:

xpath
./preceding-sibling::sibling1

Practical Example 🎯

Let's consider a more complex XML file:

xml
<bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J. K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore>

Accessing Preceding Siblings

To find the title of the preceding book (which is Everyday Italian), we can use the following XPath expression:

xpath
./preceding-sibling::book/title

Quiz Time 📝

Quick Quiz
Question 1 of 1

What is the XPath expression to select the `author` of the preceding book in the provided XML example?

That's it for today! We've covered the basics of the Preceding-Sibling Axis in XPath. In the next lesson, we'll explore more XPath axes and functions. Happy coding! 💻🎓