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>

Comments

17 Jan 2012 - 6:32am by Anonymous (not verified)

Thank you very much for sharing this information. I like this side. Its really a great article. So please give me some important information about this side.

Best Drop Shippers

17 Jan 2012 - 6:34am by Anonymous (not verified)

I think its a great topic. I like it very much. Its so interesting.So i want some information for sharing this side with some of my friend. Thanks.

Best Drop Shippers

17 Jan 2012 - 6:13pm by nevaeh (not verified)

sport watches fake tudor watches sport watches replica audemars piguet buy watches fake jaeger lecoultre mens watches.

17 Jan 2012 - 6:58pm by avenger (not verified)

sport watches replica omega replica watches cartier must replica watches replica breitling replica watches formula one tag heuer replica watches for sale rolex watch diesel watches.

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.