Finding Elements by Id 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 select elements based on their id.

The DTD of an XML file may declare that a certain attribute of an element is a unique id. An attribute designated as such can contain any value but no two id attributes can have the same value.

This example demonstrates some common uses of expressions that use element ids; 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 element id 3 String xpath = "id('3')"; // 3 // Get all e elements directly under element id 3 xpath = "id('two')/e"; // 3 4 6 // Get elements with id='two', id='3', or id='seven' xpath = "id('two 3 seven the fifth')"; // two 3 seven // Note that this method of finding elements does not work // if the id value contains a space // Get a non-existent element xpath = "id('100')"; // (none)
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"?> <!DOCTYPE root [ <!ELEMENT e (e*) > <!ATTLIST e id ID #REQUIRED> ]> <root> <e id="1"> <e id="two"> <e id="3"/> <e id="4"> <e id="the fifth"/> </e> <e id="6"/> </e> </e> <e id="seven"/> </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.