Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.Document;

import org.xml.sax.SAXException;

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

import java.io.*;

public class Main {
    public static String getFirstChildNodeValue(Document parent, String nodeName) {
        return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
    }

    public static String getNodeValue(String xml, String nodeName) throws Exception {
        Document doc = loadXMLFrom(xml);
        return getFirstChildNodeValue(doc, nodeName);
    }

    public static Document loadXMLFrom(String xml) throws Exception {
        return loadXMLFrom(new ByteArrayInputStream(xml.getBytes()));
    }

    public static Document loadXMLFrom(InputStream inputStream) throws Exception {
        Document doc = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        javax.xml.parsers.DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(inputStream);
        } catch (ParserConfigurationException pce) {
            throw new Exception(pce.getMessage());
        } catch (SAXException se) {
            throw new Exception(se.getMessage());
        } catch (IOException ioe) {
            throw new Exception(ioe.getMessage());
        } finally {
            inputStream.close();
        }
        return doc;
    }
}