According to the W3C, XPath is a language for addressing parts of an XML document, designed to be used by both XSLT and XPointer. In this article we will learn about XPath, XPath expressions and how to use XPath in .NET and Java.
Introduction to XPath - Getting Elements (Page 3 of 4 )
You can use indexing of elements to give you results similar to arrays. The /book expression selects both <book> elements. To get the first <book> element use /book. Similarly, for the second <book> element use /book or/book[last()]. The last() function identifies the last element.
//B[@id] selects B elements which have the id attribute in the following XML.
<A> <B id = "b1"/> <B id = "b2"/> <B name = "bname"/> <B/>
//B[@id='b1'] selects B elements which have the id attribute with a value of b1.
<A> <B id = "b1"/> <B name = " xyz "/> <B name = "bbb"/> </A>
The name() function returns the name of the element. Some other functions for selections are starts-with() and contains(). The //*[starts-with(name(),'B')] expression selects all elements whose names start with 'B'. The//*[contains(name(),'C')] expression selects all elements whose names contain 'C'. The string-length() function returns the length of the input string. The //*[string-length(name())>5] expression selects all the elements whose names are five or more letters long.
Several paths can be combined with the pipe ( | ) separator. The //year | //price expression selects all year and price elements.