如何在“请勿编辑此文件”注释后添加换行符?我尝试添加带有换行符的文本节点,但它不起作用。
代码:
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();
}
}
}
输出:
<!-- DO NOT EDIT THIS FILE --><projects/>