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.w3c.dom.Element;

import org.xml.sax.SAXException;

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

import java.io.*;

public class Main {
    public static String getAttributeValue(String xml, String nodeName, String attributeName) throws Exception {
        Document doc = loadXMLFrom(xml);
        return getFirstChildNodeAttributeValue(doc, nodeName, attributeName);
    }

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

    public static String getFirstChildNodeAttributeValue(Element parent, String nodeName) {
        return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
    }

    public static String getFirstChildNodeAttributeValue(Document parent, String nodeName, String attributeName) {
        return parent.getElementsByTagName(nodeName).item(0).getAttributes().getNamedItem(attributeName)
                .getNodeValue();
    }

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

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