Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;

import java.io.StringWriter;

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

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

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

import org.xml.sax.SAXException;

public class Main {
    private static String getXmlString(Document document, String tagName)
            throws ParserConfigurationException, SAXException, IOException, TransformerException {
        NodeList nodeList = document.getElementsByTagName(tagName);
        if (nodeList.getLength() < 1) {
            throw new IllegalArgumentException("no " + tagName + " found");
        }
        Node sub = nodeList.item(0);
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document subdoc = db.newDocument();
        subdoc.appendChild(sub.cloneNode(true));

        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        DOMSource domSource = new DOMSource(subdoc);
        StringWriter sw = new StringWriter();
        StreamResult xmlResult = new StreamResult(sw);
        transformer.transform(domSource, xmlResult);
        sw.flush();
        return sw.toString();
    }
}