XPath Relative Path
XPath is a language used to traverse the elements and attributes of an XML document. XPath can be used to select elements, attributes and text from an XML document. The path expressions used in XPath are known as XPath expressions. XPath expressions are used to navigate through an XML document and locate elements, attributes, and other nodes.
Syntax
The syntax of XPath Relative Path is as follows:
//element[@attribute='value']
This expression selects the element
with the specified attribute value.
Example
Consider the following XML file, named books.xml
:
<library>
<book id="001">
<title>Harry Potter and the Philosopher's Stone</title>
<author>J.K. Rowling</author>
<year>1997</year>
<price>20.00</price>
</book>
<book id="002">
<title>The Da Vinci Code</title>
<author>Dan Brown</author>
<year>2003</year>
<price>18.00</price>
</book>
<book id="003">
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<year>1951</year>
<price>15.00</price>
</book>
</library>
We can use the following XPath expression to select all the book titles:
//book/title
This expression selects the title
element for all book
elements in the library
node.
Output
The output of the above XPath expression will be:
Harry Potter and the Philosopher's Stone
The Da Vinci Code
The Catcher in the Rye
Explanation
The //
symbol in XPath selects all nodes at any level, so //book
selects all book
elements in the document. Then, the /title
selects the title
element of each book
.
Use
XPath expressions can be used to retrieve specific elements, attributes, and other types of nodes within an XML document. This can be useful for parsing and processing XML data.
Important Points
- XPath is used to locate elements and attributes in an XML document.
- XPath uses path expressions to select elements based on their location relative to other elements in the document.
- The
/
symbol is used to select immediate child nodes, while the//
symbol selects all descendant nodes.
Summary
XPath Relative Path is used to select elements, attributes and other nodes based on their location relative to other elements in an XML document. XPath expressions can be used to retrieve specific data from an XML file, making it useful for parsing and processing XML data.