How to remove empty lines when deleting XML in dom4j.
To remove empty lines when parsing an XML file with dom4j, you can achieve this by setting the output format to remove empty lines. Here are the specific steps:
- Create an XML document object.
Document document = DocumentHelper.createDocument();
- Add elements such as root elements and child elements.
Element root = document.addElement("root");
Element child1 = root.addElement("child1");
Element child2 = root.addElement("child2");
- Output the XML file and set the formatting for output.
OutputFormat format = OutputFormat.createPrettyPrint();
format.setTrimText(true); // 去掉文本节点两边的空白
format.setNewlines(true); // 是否换行
format.setIndent(true); // 是否缩进
format.setIndentSize(2); // 缩进空格数
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"), format);
writer.write(document);
writer.close();
By setting format.setTrimText(true), you can remove the whitespace on both sides of the text node, thereby achieving the purpose of removing empty lines.