Welcome to our tutorial on XPath Axes! In this lesson, we'll explore how to navigate an XML document using XPath, focusing on various axes that help you move between and select elements. Let's get started! 📝
XPath (XML Path Language) is a language used to navigate XML documents. It provides a syntax for addressing parts of an XML document, making it easy to retrieve and manipulate data.
XPath uses axes to traverse an XML document, enabling you to navigate through its structure and select elements based on relationships. Let's delve into the core axes:
/): Selects elements that are immediate children of a specified element.<root>
<element1>Content 1</element1>
<element2>Content 2</element2>
</root>
XPath expression: /root/element1
Result: <element1>Content 1</element1>//): Selects elements that are nested at any level within the specified element.<root>
<element1>Content 1</element1>
<child>
<element2>Content 2</element2>
</child>
</root>
XPath expression: //element2
Result: <element2>Content 2</element2>..): Selects the parent element of the current element.<root>
<element1>Content 1</element1>
</root>
XPath expression: . (current node) or element1/..
Result: <root>@): Selects attributes of an element.<element attr="value">Content</element>
XPath expression: //element/@attr
Result: `value`.) and Context (.)): Refers to the current node.<element>Content</element>
XPath expression: . or element
Result: <element>Content</element>//) and Following-Sibling (//): Selects elements that come after the current element or its sibling.<root>
<element1>Content 1</element1>
<element2>Content 2</element2>
</root>
XPath expression: /root/element1/following::element2
Result: <element2>Content 2</element2>
XPath expression: /root/element1/following-sibling::element2
Result: <element2>Content 2</element2>//) and Preceding-Sibling (//): Selects elements that come before the current element or its sibling.<root>
<element2>Content 2</element2>
<element1>Content 1</element1>
</root>
XPath expression: /root/element2/preceding::element1
Result: <element1>Content 1</element1>
XPath expression: /root/element2/preceding-sibling::element1
Result: <element1>Content 1</element1>Which axis is used to select elements that are immediate children of a specified element?
Stay tuned for our next lesson, where we'll delve deeper into XPath and learn about advanced techniques for navigating and selecting elements in XML documents. 📝
Happy coding! 🎉