Java XPath Select selectSingleElement(Element element, String xpathExpression)

Here you can find the source of selectSingleElement(Element element, String xpathExpression)

Description

select Single Element

License

Open Source License

Declaration

static public Element selectSingleElement(Element element,
            String xpathExpression) throws Exception 

Method Source Code

//package com.java2s;
//License from project: GNU General Public License 

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

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    static public Element selectSingleElement(Element element,
            String xpathExpression) throws Exception {
        if (xpathExpression.indexOf("/") == -1) {
            NodeList nodeList = element.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE
                        && node.getNodeName().equals(xpathExpression)) {
                    return (Element) node;
                }//from   www. java  2  s. c  o  m
            }
            //  NodeList nodes = element.getElementsByTagName(xpathExpression);
            //  if (nodes.getLength() > 0) {
            //      return (Element) nodes.item(0);
            //  } else {
            return null;
            //  }
        } else {
            XPath xpath = XPathFactory.newInstance().newXPath();
            Element node = (Element) xpath.evaluate(xpathExpression,
                    element, XPathConstants.NODE);
            return node;
        }
    }
}

Related

  1. selectNodes(String xPath, Node target)
  2. selectNodes(String xpath, Object node)
  3. selectNodes(String xpath, Object node)
  4. selectNodesViaXPath(XPath xPath, Node startingNode, String xPathExpression)
  5. selectNodeText(Node node, String expression)
  6. selectSingleNode(final Node node, final String xPath)
  7. selectSingleNode(final Node sourceNode, final String xPathExpression)
  8. selectSingleNode(Node node, String xpath, NamespaceContext context)
  9. selectString(String xpath, Object node)