Java XML Element First getFirstNode(Document doc, String xPathExpression)

Here you can find the source of getFirstNode(Document doc, String xPathExpression)

Description

Get first node on a Document doc, give a xpath Expression

License

Apache License

Parameter

Parameter Description
doc a parameter
xPathExpression a parameter

Return

a Node or null if not found

Declaration

public static Node getFirstNode(Document doc, String xPathExpression) 

Method Source Code


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

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.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**/*from  www.  ja  va 2  s  .  co  m*/
       * Get first node on a Document doc, give a xpath Expression
       * 
       * @param doc
       * @param xPathExpression
       * @return a Node or null if not found
       */
    public static Node getFirstNode(Document doc, String xPathExpression) {
        try {

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr;
            expr = xpath.compile(xPathExpression);
            NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            return nl.item(0);

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related

  1. getFirstElementByTagName(Document doc, String tagName)
  2. getFirstElementByTagName(Document document, String name)
  3. getFirstElementByTagName(Document document, String tag)
  4. getFirstElementText(Document document, String tagName)
  5. getFirstImageTransformElement(final Document doc)
  6. getFirstNodeByName(Document d, String s)