Selecting from a Set of Child Elements in a DOM Document Using XPath

XPath is an expression language for selecting nodes in an XML file. See Finding Elements by Absolute Location in a DOM Document Using XPath for common XPath expression for selecting elements. This example adds to those examples by demonstrating the ability to apply a selection filter to a set of child elements. For example, if an element A contained several B elements, you could include only the first B element or all but the first B element.

Filtering in XPath is specified with a predicate after the element name. A predicate has the form [expression]. For example,

/book/chapter[2]/section[3]
selects the 3rd section element from the 2nd chapter element under the root element book.

This example demonstrates some common filters; for more information on XPath, see the specification at http://www.w3c.org/TR/xpath. In the example, the result of an XPath expression is shown next to the expression; the numbers are ids of elements in the sample file shown at the end of the example.

// Get the first element under the root String xpath = "/*/*[1]"; // 2 // Get the second elem1 element under the root xpath = "/root/elem1[2]"; // 8 // Get all first-born e elements in the document; that is, for all // e elements with e element siblings, include only the first sibling xpath = "//e[1]"; // 4 6 10 12
Note that //e[1] does not return the first e element in the document because the [1] predicate applies to e, which represents the set of e elements under one element and not to //e, which represents the set of e elements in the document. The following expression retrieves the first e element in the document:
// Get the first e element in the document xpath = "(//e)[1]"; // 4 // For all e elements with e element siblings, include only // the first 3 siblings xpath = "//e[position() <= 3]"; // 4 6 10 11 12 // Get all last-born e elements in the document; that is, for all // e elements with e element siblings, include only the last sibling xpath = "//e[last()]"; // 4 6 11 12 // Get the last e element in the document xpath = "(//e)[last()]"; // 12
To execute an XPath expression, see Finding Elements by Absolute Location in a DOM Document Using XPath. Here is the sample XML file used in the example:
<?xml version="1.0" encoding="UTF-8"?> <root id="1"> <elem1 id="2"> <elem2 id="3"> <e id="4"/> <elem3 id="5"> <e id="6"/> </elem3> <elem3 id="7"/> </elem2> </elem1> <elem1 id="8"> <elem2 id="9"/> <e id="10"/> <e id="11"/> </elem1> <e id="12"/> </root>

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.