Directly on the code:
Import part:
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileOutputStream;
public static void xmlWriterWithFormat(Document doc,File xmlFile) throws Exception { XMLWriter xmlWriter = null; OutputFormat format = OutputFormat.createPrettyPrint(); //Set XML document output format format.setEncoding("UTF-8"); //Set XML The encoding type of the document format.setIndent(true); //Set whether to indent format.setIndent(" "); //Realize indentation with spaces format.setNewlines(true); //Set whether to wrap try{ xmlWriter = new XMLWriter(new FileOutputStream(xmlFile), format); xmlWriter.write(doc); } catch(Exception e) { throw new Exception(e); } finally { if(xmlWriter!=null) {
xmlWriter.close();
}
}
}