Thursday, January 06, 2005
Finding Elements by Content in a DOM Document Using XPath (Java Developers Almanac Example)
Finding Elements by Content in a DOM Document Using XPath (Java Developers Almanac Example)
This example demonstrates some common uses of expressions that use element content; 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 all elements that equal the string cat
String xpath = "//*[.='cat']"; // 2 6
// Get all elements that equal the string dog
xpath = "//*[.='dog']"; // (none)
// Note that element #3 does not match because its
// content is " dog " rather than "dog"
// Get all elements that contain the string cat
xpath = "//*[contains(.,'cat')]"; // 1 2 4 5 6
// Get all elem3 elements that contain the string cat
xpath = "//elem3[contains(.,'cat')]"; // 6
// Get all elements that contain the string cat,
// ignoring the contents of any subelements
xpath = "//*[contains(child::text(),'cat')]"; // 2 4 6
// Get all elements without subelements and whose contents contains the string cat
xpath = "//*[count(*)=0 and contains(.,'cat')]"; // 2 6