简体   繁体   中英

How to add line break into XML file with Java?

How to add line break after the "do not edit this file" comment? I've tried to add textnode with line break but it doesn't work.

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();
        }
    }
}

Output:

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

I have a blank line as well when I ran your code. Are you viewing the file in an editor, or parsing and displaying it? I ask because xml:space="preserve" settings might be wonky in your parser code if that's the case.

The other option is to put the comment within the XML root 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 interoperable. For example let's say you use xinclude to embed then in the final version of the file. The way you have in your question the notice to not edit the file will not be included. If you put it within the root element it will (and you should probably change it to say something about not editing the contents of this project element, rather than saying file for the same reason).

There is no newLine after the comment since, even if you activated the indentation, the comment and the following node have depth 0.

You can add a new line character in XML file by using: \n or:

<string name="yourString">new line starts now \n this is a new line</string>

Also, you should rethink the formatting of your text to not using the angle brackets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM