我有一个以下的xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<reRoot>
<reNode> world</reNode>
</reRoot>
我想在附加文本后显示我的xml文件,
Linesaddedbeforexml
<?xml version="1.0" encoding="UTF-8"?>
<reRoot>
<reNode> world</reNode>
</reRoot>
Linesaddedafterxml
如何实现这个使用java,我试过Filewriter但写完之后对齐不正确。 在示例逻辑代码的解决方案中需要帮助。
答案 0 :(得分:0)
该主题的答案发布在另一个非常有帮助的帖子上。
how to append text in top and end of the .xml file using java?
答案 1 :(得分:-1)
使用Filewritter编写文本后,您可以按如下方式格式化xml
public static String prettyFormat(String input) {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", 2);
transformer.transform(xmlInput, new StreamResult(stringWriter));
String pretty = stringWriter.toString();
pretty = pretty.replace("\r\n", "\n");
return pretty;
} catch (Exception e) {
throw new RuntimeException(e);
}
}