Using the following simple code:
package test;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class TestOutput
A little util class as an example...
import org.apache.xml.serialize.XMLSerializer;
public class XmlUtil {
public static Document file2Document(File file) throws Exception {
if (file == null || !file.exists()) {
throw new IllegalArgumentException("File must exist![" + file == null ? "NULL"
: ("Could not be found: " + file.getAbsolutePath()) + "]");
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
return dbFactory.newDocumentBuilder().parse(new FileInputStream(file));
}
public static Document string2Document(String xml) throws Exception {
InputSource src = new InputSource(new StringReader(xml));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
return dbFactory.newDocumentBuilder().parse(src);
}
public static OutputFormat getPrettyPrintFormat() {
OutputFormat format = new OutputFormat();
format.setLineWidth(120);
format.setIndenting(true);
format.setIndent(2);
format.setEncoding("UTF-8");
return format;
}
public static String document2String(Document doc, OutputFormat format) throws Exception {
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.serialize(doc);
return stringOut.toString();
}
public static String document2String(Document doc) throws Exception {
return XmlUtil.document2String(doc, XmlUtil.getPrettyPrintFormat());
}
public static void document2File(Document doc, File file) throws Exception {
XmlUtil.document2String(doc, XmlUtil.getPrettyPrintFormat());
}
public static void document2File(Document doc, File file, OutputFormat format) throws Exception {
XMLSerializer serializer = new XMLSerializer(new FileOutputStream(file), format);
serializer.serialize(doc);
}
}
XMLserializer is provided by xercesImpl from the Apache Foundation. Here is the maven dependency:
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>
You can find the dependency for your favourite build tool here: http://mvnrepository.com/artifact/xerces/xercesImpl/2.11.0.
The missing part is the amount to indent. You can set the indentation and indent amount as follow:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
To make the output a valid XML document, NO. A valid XML document must start with a processing instruction. See the XML specification http://www.w3.org/TR/REC-xml/#sec-prolog-dtd for more details.
You could probably prettify everything with an XSLT file. Google throws up a few results, but I can't comment on their correctness.