With JDK 1.8.0, you can use the built-in XMLSerializer (which was introduced in JDK 1.4 as a branch of Apache Xerces).
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
Document doc =
java.io.Writer writer = new java.io.FileWriter("MyOutput.xml");
XMLSerializer xml = new XMLSerializer(writer, null);
xml.serialize(doc);
Use a type object OutputFormatto configure the output, for example, like this:
OutputFormat format = new OutputFormat(Method.XML, StandardCharsets.UTF_8.toString(), true);
format.setIndent(4);
format.setLineWidth(80);
format.setPreserveEmptyAttributes(true);
format.setPreserveSpace(true);
XMLSerializer xml = new XMLSerializer(writer, format);
Please note that classes from are com.sun.*not documented and therefore are usually not considered as the preferred way of working. However, javax.xml.transform.OutputKeysyou cannot specify, for example, the size of the indentation or the width of the line. So, if this is important, then this solution should help.
source
share