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!
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 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:
<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.
To select the preceding siblings using XPath, you can use the preceding-sibling function. The syntax is as follows:
./preceding-sibling::nodeNameIn our example, if we want to select sibling1, the XPath expression would be:
./preceding-sibling::sibling1Let's consider a more complex XML file:
<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>To find the title of the preceding book (which is Everyday Italian), we can use the following XPath expression:
./preceding-sibling::book/titleWhat 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! 💻🎓