XPath

Find elements by attributes with XPath

In this example we shall show you how to find elements by attributes using XPath. The XPath language provides a simple, concise syntax for selecting nodes from an XML document. To find elements by attributes using XPath one should perform the following steps:

  • Obtain a new instance of a DocumentBuilderFactory, that is a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
  • Set the parser produced so as not to validate documents as they are parsed, using setValidating(boolean validating) API method of DocumentBuilderFactory, with validating set to false.
  • Create a new instance of a DocumentBuilder, using newDocumentBuilder() API method of DocumentBuilderFactory.
  • Parse the FileInputStream with the content to be parsed, using parse(InputStream is) API method of DocumentBuilder. This method parses the content of the given InputStream as an XML document and returns a new DOM Document object.
  • Create an XPathFactory instance to be used to create XPath objects, with newInstance() API method of XPathFactory.
  • Create a new XPath object, using the underlying object model determined when the XPathFactory was instantiated, with newXPath() API method of XPathFactory.
  • Create a String expression and use evaluate(String expression, Object item, QName returnType) API method of XPath in order to evaluate it in the specified Document object. The method returns a result as the specified type.
  • In the example, first we set an expression to search all elements whose attribute 'key‘ is set to a specific value. Then we create an expression to search all elements that have the attribute 'key'. We are also searching for all elements that contain more than one specified attributes. Finally, we are searching for all elements in a specified entry that contain a specified attribute. In all cases the returnType is set to XPathConstants.NODESET, and a NodeList is returned, that is a collection of the Node objects containing the specified content,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class FindElementsByAttributesWithXPath {

	public static void main(String[] args) throws Exception {
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(false);
		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document doc = db.parse(new FileInputStream(new File("in.xml")));
		
		XPathFactory factory = XPathFactory.newInstance();
		
		XPath xpath = factory.newXPath();
		
		String expression;
		NodeList nodeList;
		
		// 1. all elements where attribute 'key' equals 'mykey1'
		expression = "//*[@key='mykey1']";;
		nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
		System.out.print("1. ");
		for (int i = 0; i < nodeList.getLength(); i++) {
			System.out.print(nodeList.item(i).getNodeName() + " ");
		}
		System.out.println();
		
		// 2. all elements where attribute 'key' equals 'mykey'
		expression = "//*[contains(@key,'mykey')]";
		nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
		System.out.print("1. ");
		for (int i = 0; i < nodeList.getLength(); i++) {
			System.out.print(nodeList.item(i).getNodeName() + " ");
		}
		System.out.println();
		
		// 3. all elements that have the key attribute
		expression = "//*[@key]";
		nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
		System.out.print("3. ");
		for (int i = 0; i < nodeList.getLength(); i++) {
			System.out.print(nodeList.item(i).getNodeName() + " ");
		}
		System.out.println();

		// 4. all elements that have both key and attr attributes
		expression = "//*[@key and @attr]";
		nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
		System.out.print("4. ");
		for (int i = 0; i < nodeList.getLength(); i++) {
			System.out.print(nodeList.item(i).getNodeName() + " ");
		}
		System.out.println();
		
		// 5. all entry elements that have the key attribute
		expression = "//entry[@key]";
		nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
		System.out.print("5. ");
		for (int i = 0; i < nodeList.getLength(); i++) {
			System.out.print(nodeList.item(i).getNodeName() + " ");
		}
		System.out.println();
		
	}

}

Input:

<?xml version="1.0" encoding="UTF-8"?>
<entries>
    <entry key="mykey1" attr="attr1"/>
    <entry key="mykey2" attr="attr2"/>
    <otherentry key="mykey1" attr="attr3"/>
    <entry key="mykey4"/>
    <otherentry key="mykey4"/>
</entries>

Output:

1. entry otherentry 
1. entry entry otherentry entry otherentry 
3. entry entry otherentry entry otherentry 
4. entry entry otherentry 
5. entry entry entry

 
This was an example of how to find elements by attributes using XPath in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button