![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e1077. Finding Elements by Id in a DOM Document Using XPathXPath is an expression language for selecting nodes in an XML file. See e1074 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 e1074 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>
e1075. Selecting from a Set of Child Elements in a DOM Document Using XPath e1076. Finding Elements by Content in a DOM Document Using XPath e1078. Finding Elements by Attributes in a DOM Document Using XPath
© 2002 Addison-Wesley. |