Java XPath Get getNodeTextByXPath(Document doc, String xpath)

Here you can find the source of getNodeTextByXPath(Document doc, String xpath)

Description

get Node Text By X Path

License

Open Source License

Declaration

public static String getNodeTextByXPath(Document doc, String xpath) 

Method Source Code

//package com.java2s;
/* Copyright (c) 2013 Intecs - www.intecs.it. All rights reserved.
 * This code is licensed under the GPL 3.0 license, available at the root
 * application directory./*w ww. j  a v a2  s .  com*/
*/

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    public static String getNodeTextByXPath(Document doc, String xpath) {
        try {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpathEn = factory.newXPath();
            return xpathEn.evaluate(xpath, doc);
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    public static String getNodeTextByXPath(Element eoEl, String xpath) {
        try {
            Document doc = newDocument();
            Element importedEl = (Element) doc.importNode(eoEl.cloneNode(true), true);
            doc.appendChild(importedEl);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpathEn = factory.newXPath();
            return xpathEn.evaluate(xpath, doc);
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    public static Document newDocument() throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        return documentBuilder.newDocument();
    }
}

Related

  1. getNodesByPath(String path, Element localElement, Document doc)
  2. getNodesByXPath(Document doc, XPathExpression expr)
  3. getNodesByXPath(Element parent, String name)
  4. getNodesListXpathNode(final String xPath, final Node node)
  5. getNodeText(XPath xpath, String xp, Node n)
  6. getNogeList(String path, Node node)
  7. getORSVersion()
  8. getProcessIdFromBpmn(final String bpmn)
  9. getPublicKeyFromKeyInfo(Node keyInfoNode)