Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.StringWriter;

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.apache.log4j.Logger;
import org.w3c.dom.Document;

public class Main {
    /**
     * creating logger log4j
     */
    static Logger logger = Logger.getLogger("org.apache.log4j.PatternLayout");

    /**
     * method used to convert a xml document to a string
     * 
     * @param doc
     * @return
     */
    public static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;

        try {
            /**
             * transformation of document happens here
             */
            transformer = tf.newTransformer();
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();

            /**
             * logging success
             */
            logger.info("xml conversion to string  successful Class:XMLParserUtility line# 98");

            return output;

        } catch (TransformerException e) {
            e.printStackTrace();
            logger.fatal("Could not transform document to XML", e);
        }
        return null;
    }
}