生成的文件如下所示:
<Messages><Message Name="Foo">FooMessage</Message><Message Name="Bar">BarMessage</Message></Messages>
<xml version="1.0" encoding="us-ascii">
<!-- Message Documentation -->
<!-- Version 1.0 -->
<Messages>
<Message Name="Foo">FooMessage</Message>
<Message Name="Bar">BarMessage</Message>
</Messages>
但在我通过转换器运行它以漂亮地打印xml之后,它会导致注释被压缩到一行:
<xml version="1.0" encoding="us-ascii">
<!-- Message Documentation --><!-- Version 1.0 -->
<Messages>
<Message Name="Foo">FooMessage</Message>
<Message Name="Bar">BarMessage</Message>
</Messages>
标头只是一个包含注释的文件:
<!-- Message Documentation -->
<!-- Version 1.0 -->
这就是我目前正在做的(注意messages.xml是生成的文件):
public static void generate() throws Exception {
List <String> header = Files.readAllLines(Paths.get("header.xml"));
List <String> message = Files.readAllLines(Paths.get("messasges.xml"));
StringBuilder sb = new StringBuilder();
for (String s: header) {
sb.append(String.format("%s%n", s));
}
for (String s: message) {
sb.append(String.format("%s%n", s));
}
Files.write(Paths.get("tmp.xml"), sb.toString.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
DocumentBuilder db = DocumentBuilderFactor.newInstance().newDocumentBuilder();
Document doc = db.parse(Paths.get("tmp.xml").toFile());
String xmlStr = prettyPrint(doc);
}
public static String prettyPrint(Document doc) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", 4);
transformer.setOutputProperty(OutputKeys.ENCODING, "us-ascii");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
return writer.getBuffer().toString();
}
如果有任何帮助,我将不胜感激,因为我还没有找到任何关于在他们各自的行中保留评论的信息。