Return one element based on xPath - Java XML

Java examples for XML:XPath

Description

Return one element based on xPath

Demo Code


//package com.java2s;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    /**//from w  ww .j  av  a  2 s .  c  om
     * Return one element based on xPath
     */
    static Element getElementByAttribute(Document doc, String xPath) {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = null;
        NodeList nl = null;
        try {
            expr = xpath.compile(xPath);
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return (Element) nl.item(0);
    }
}

Related Tutorials