Select Single Element from parent Element using XPath - Java XML

Java examples for XML:XPath

Description

Select Single Element from parent Element using XPath

Demo Code

// This program is free software; you can redistribute it and/or modify it
//package com.java2s;
import org.w3c.dom.*;

import javax.xml.xpath.*;

public class Main {
    public static Element SelectSingleElement(Element parent,
            String expression) {/* ww w .j a va 2  s  . co m*/
        Element element = null;
        XPath xpath = getXPath();
        try {
            XPathExpression xpathExpression = xpath.compile(expression);
            element = (Element) xpathExpression.evaluate(parent,
                    XPathConstants.NODE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return element;
    }

    public static XPath getXPath() {
        return getXPathFactory().newXPath();
    }

    public static XPathFactory getXPathFactory() {
        return XPathFactory.newInstance();
    }
}

Related Tutorials