parse Dom To Xml String - Java XML

Java examples for XML:DOM

Description

parse Dom To Xml String

Demo Code

//package com.java2s;

import java.io.StringWriter;

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

public class Main {
    public static String parseDomToXml(Document xml) {

        try {/*from w ww .  j a  va2 s .  c  o  m*/
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer xform = factory.newTransformer();

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(xml), new StreamResult(
                    writer));
            return writer.getBuffer().toString().replaceAll("\n|\r", "");
        } catch (Exception err) {
            err.printStackTrace();
            return null;
        }
    }
}

Related Tutorials