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.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import java.io.*;

public class Main {
    public static String XMLtoString(Node node) throws Exception {
        Document document = node.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
        LSSerializer serializer = domImplLS.createLSSerializer();
        serializer.getDomConfig().setParameter("xml-declaration", false);
        return serializer.writeToString(node);
    }

    public static String XMLtoString(Document doc) throws Exception {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer;
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            return writer.getBuffer().toString();
        } catch (TransformerException te) {
            throw new Exception(te.getMessageAndLocation());
        }
    }

    public static String transform(String xmlString, String stylesheetPathname) throws Exception {
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            Source stylesheetSource = new StreamSource(new File(stylesheetPathname).getAbsoluteFile());
            Transformer transformer = factory.newTransformer(stylesheetSource);
            Source inputSource = new StreamSource(new StringReader(xmlString));
            Writer outputWriter = new StringWriter();
            Result outputResult = new StreamResult(outputWriter);
            transformer.transform(inputSource, outputResult);
            return outputWriter.toString();
        } catch (TransformerConfigurationException tce) {
            throw new Exception(tce.getMessageAndLocation());
        } catch (TransformerException te) {
            throw new Exception(te.getMessageAndLocation());
        }
    }
}