Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//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.
 */

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();
    }
}