Java XML Element Get getElement(final Document doc, final String expression)

Here you can find the source of getElement(final Document doc, final String expression)

Description

Get one element from XML document using xpath expression

License

Apache License

Parameter

Parameter Description
doc a parameter
expression a parameter

Exception

Parameter Description
XPathExpressionException an exception

Declaration

public static Element getElement(final Document doc, final String expression) throws XPathExpressionException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.logging.Logger;

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;

public class Main {
    private static Logger log = Logger.getLogger("XmlUtils");

    /**/*  w  ww .j  a  v  a  2 s .  c o m*/
     * Get one element from XML document using xpath expression
     * 
     * @param doc
     * @param expression
     * @return
     * @throws XPathExpressionException
     */
    public static Element getElement(final Document doc, final String expression) throws XPathExpressionException {
        if (null == expression || expression.isEmpty() || null == doc) {
            return null;
        }
        log.finer("Executing xpath xpression " + expression);
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xPath.compile(expression);
        Object result = expr.evaluate(doc, XPathConstants.NODE);
        return (Element) result;
    }
}

Related

  1. getElement(Element element, String name, int index)
  2. getElement(Element element, String tag)
  3. getElement(Element element, String tagName)
  4. getElement(Element element, String tagName, String namespace)
  5. getElement(Element root, String name)
  6. getElement(SOAPMessage message, String tagname, String nsURI, int whichOne)
  7. getElementArray(Element config, String elementName)
  8. getElementAsBoolean(Element e, String name)
  9. getElementAsFloat(Element e, String name, Float dft)