When saving an XML file in Java, multiple runs show that after each run, a line of white space is added between the elements, and the most recently inserted data is normal. How to solve this problem?
public class OperateXml {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/main/resources/chunkInfo/chunk.xml");
add(document);
saveDocument(document, new File("src/main/resources/chunkInfo/chunk.xml"));
} catch (Exception e) {
}
}
public static void saveDocument(Document document, File xmlFile) {
TransformerFactory tff = TransformerFactory.newInstance();
tff.setAttribute("indent-number", 2);
try {
Transformer tf = tff.newTransformer();
tf.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "chunk.dtd");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(document), new StreamResult(xmlFile));
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
public static void add(Document document) {
Element root = document.getDocumentElement();
Element chunk = document.createElement("chunk");
root.appendChild(chunk);
chunk.setAttribute("id", "id_8");
Element name = document.createElement("name");
name.setTextContent("test_6");
chunk.appendChild(name);
Element type = document.createElement("type");
type.setTextContent("log");
chunk.appendChild(type);
Element item = document.createElement("item");
item.setTextContent("2,3,4,5");
chunk.appendChild(item);
}
}
The result of saving XML file is:
CodePudding user response:
May be it's a result of a known bug in Java9 or later.
For further details see: https://bugs.openjdk.org/browse/JDK-8262285?attachmentViewMode=list