All Downloads are FREE. Search and download functionalities are using the official Maven repository.

liquibase.util.xml.DefaultXmlWriter Maven / Gradle / Ivy

There is a newer version: 4.30.0
Show newest version
package liquibase.util.xml;

import org.w3c.dom.Document;

import javax.xml.transform.OutputKeys;
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 java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class DefaultXmlWriter implements XmlWriter {

    public void write(Document doc, OutputStream outputStream) throws IOException {
//        OutputFormat format = new OutputFormat(doc);
//        format.setIndenting(true);
//        format.setEncoding("UTF-8");
//        XMLSerializer serializer = new XMLSerializer(outputStream, format);
//        serializer.asDOMSerializer();
//        serializer.serialize(doc);

        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            try {
                factory.setAttribute("indent-number", 4);
            } catch (Exception e) {
                ; //guess we can't set it, that's ok
            }

            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

            //need to nest outputStreamWriter to get around JDK 5 bug.  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
            transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(outputStream, "utf-8")));
        } catch (TransformerException e) {
            throw new IOException(e.getMessage());
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy