Asfak's Blog

Xml indentation with dom4j

Advertisements


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.FlyweightProcessingInstruction;

public class XmlOutput {

public static void writeDocument(Document doc, File df) {
df.getParentFile().mkdirs();
try {

//Step 1
OutputFormat format = OutputFormat.createPrettyPrint();
//Step 2
format.setTrimText(false);
//Step 3
format.setIndentSize(4);


XMLWriter writer = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(df), “UTF-8”), format);
FlyweightProcessingInstruction xmlDeclaration = new FlyweightProcessingInstruction(
“xml”,
“version=\”1.0\” encoding=\”UTF-8\” standalone=\”no\” “);
writer.write(xmlDeclaration);
writer.write(doc.processingInstructions());
writer.write(doc.getDocType());
writer.write(doc.getRootElement());
writer.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}

Advertisements

Advertisements