Finding Elements by Attributes 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 attributes.

This example demonstrates some common uses of expressions that use attributes; 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 where pet equals cat
String xpath = "//*[@pet='cat']";                // 2

// Get all elements where pet equals dog
xpath = "//*[@pet='dog']";                       // 7
// Note that element #3 does not match because the attribute
// value is " dog " rather than "dog"

// Get all elements where pet contains the string dog
xpath = "//*[contains(@pet,'dog')]";             // 3 7

// Get all elements that have the age attribute
xpath = "//*[@age]";                             // 3 6

// Get all elem1 elements that have the age attribute
xpath = "//elem1[@age]";                         // 3

// Get all elements that have both pet and age attributes
xpath = "//*[@pet and @age]";                    // 1 3
XPath 1.0 does not support case-insensitive matches. However, a simple case-insensitive match can be done using the translate() function, which converts a string by mapping one character into another:
// Get all elements where pet contains the string cat, ignoring case
xpath = "//*[contains(translate(@pet,'abcdefghijklmnopqrstuvwxyz',"
    + " 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),'CAT')]";  // 2 4
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" pet="cat"/>
    <elem1 id="3" pet=" dog " age="8"/>
    <elem1 id="4" pet="Cat" >
        <elem2 id="5">
            <elem3 id="6" age="10"/>
        </elem2>
    </elem1>
    <elem1 id="7" pet="dog"/>
</root>

Comments

26 May 2010 - 7:01pm by Matt Cook (not verified)

How can one display the contents of an attribute of a node selected like this?

20 Jan 2011 - 8:00am by Paul Balm (not verified)

You can access the contents of an attribute of a node selected like this as follows:
Given the XML from the example, the following will print the "pet" attributes of all :

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/root/elem1");
NodeList elem1List = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
expr = xpath.compile("@pet");
for (int i = 0; i < elem1List.getLength(); i++) {
System.out.println(expr.evaluate(elem1List.item(i), XPathConstants.STRING));
}

In this case all are under . If, e.g., some are under root and others are in other places, and you want to select them all, use "//elem1" instead of "/root/elem1".

3 Aug 2011 - 2:57am by Iluviel (not verified)

Thanks you very much!

3 Aug 2011 - 2:57am by Iluviel (not verified)

Thanks you very much!

6 Oct 2011 - 6:02pm by tiffany jewelry (not verified)

ical level, all the while maintaining a sense of class reb bull hats and elegance that appealed to the elitest of women. She nfl hats cheap ical level, all the while maintaining a sense of class sterling silver rings and elegance that appealed to the elitest of women. She china jewelry online ical level, all the while maintaining a sense of class tiffany jewelry on sale and elegance that appealed to the elitest of women. She tiffany jewelry

10 Oct 2011 - 8:53pm by Anonymous (not verified)

40 years ago, The north face store's introduction unknown. 40 years later, north face outlet store has become high-performance apparel, footwear and other equipment and a rich product suppliers. We continue to innovate beyond the limit, to help you continue to explore the limits of a breakthrough. The world's most prominent climbers, mountaineers, extreme skiers, skate skiers, endurance athletes, and explorers have preferred The cheap north face, we are proud of. Moreover, in the new millennium approaching, The cheap northface jackets launched its own series of hiking and cross country running shoes, for those who never move to the next target of a new outdoor sports enthusiasts with the most intimate products.

15 Nov 2011 - 1:09am by Anonymous (not verified)
17 Jan 2012 - 4:08am by Anonymous (not verified)

Its really a good article. This site is so helpful. I want to know some other information about this post. So please give some other information about this side.

Best Drop Shippers/a>

17 Jan 2012 - 6:41pm by internet savvy (not verified)

I am a real dead-mouth so while i think that is a fab idea, i don’t want to write one, i’d rather read. I do think that is a kind idea. But I love it! Thanks and Truly.

internet savvy
www.tulleeho.org

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.