Serializing XML DOMs using Xerces/Xalan

From Stack Overflow
Jump to: navigation, search
// XML classes
import org.w3c.dom.Document;
import javax.xml.parsers.*;
import java.io.*;

// Serialization classes
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.OutputFormat;

public class TestSerialize {
    /** Test document, not pretty-print formatted */
    public static final String TEST_DOC = 
        "<MyDoc \n\n\n" +
        "name=\"test\">\n\n\n" +
        "<Ninja><Monkey>1</Monkey><Monkey>2</Monkey>\n" +
        "</Ninja></MyDoc>"; 

    public static void main(String[] args) throws Exception {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
            new ByteArrayInputStream(TEST_DOC.getBytes()));
        File output = File.createTempFile("SerializeTest", ".xml");
        FileOutputStream out = new FileOutputStream(output);
        OutputFormat outputFormat = new OutputFormat();
        
        outputFormat.setOmitComments(false);
        outputFormat.setIndenting(true);
        outputFormat.setIndent(4);
        outputFormat.setPreserveSpace(false);
        
        XMLSerializer serializer = new XMLSerializer(outputFormat);
        serializer.setOutputByteStream(out);
        serializer.serialize(doc);
        out.close();
        System.out.println("Output is pretty printed at: " + output.getCanonicalPath());
    }
}
Personal tools