How to add line break in XML file with Java?

How to add a line break after the comment "do not edit this file"? I tried adding a textnode with line break, but it does not work.

the code:

import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main { public static void main(String[] args) { try { final Document doc = DocumentBuilderFactory.newInstance(). newDocumentBuilder().newDocument(); doc.appendChild(doc.createComment(" DO NOT EDIT THIS FILE ")); final Element rootElement = doc.createElement("projects"); doc.appendChild(rootElement); final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(new DOMSource(doc), new StreamResult(new File("C:/abc.xml"))); } catch ( Exception e ) { e.printStackTrace(); } } } 

Conclusion:

 <!-- DO NOT EDIT THIS FILE --><projects/> 

Jmf2h.png

+6
source share
2 answers

I have an empty line when I run your code. Are you viewing the file in the editor or parsing it and showing it? I ask because the parameters xml: space = "save" may be inconvenient in your parser code, if this is the case.

Another option is to put a comment in the root XML element itself:

  final Element rootElement = doc.createElement("projects"); doc.appendChild(rootElement); rootElement.appendChild(doc.createComment(" DO NOT EDIT THIS FILE ")); 

In several ways, this is more compatible. For example, suppose you use xinclude to embed in the final version of a file. The way in your question, the notification that you are not editing the file, will not be included. If you put it in the root element, it will (and you probably should change it to say something about not editing the contents of this project element, and not saying the file for the same reason).

0
source

After the comment there is no newLine, since even if you have indented, the comment and the following nodes have a depth of 0.

0
source

Source: https://habr.com/ru/post/922120/


All Articles