我知道在 stackoverflow 上有很多关于从 Java 写入 XML 的问题,但它们太复杂了。我觉得我有一个非常简单的问题,我就是想不通。
所以我有一个程序需要大量的用户输入,我目前正在创建一个文本文档并将结果附加到一个文本文档中。我将在这里发布我的作者代码:
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("C:/Documents and Settings/blank/My Documents/test/test.txt", true)));
out.println("");
out.println("<event title=\""+titleFieldUI+"\"");
out.println(" start=\""+monthLongUI+" "+dayLongUI+" "+yearLongUI+" 00:00:00 EST"+"\"");
out.println(" isDuration=\"true\"");
out.println(" color=\""+sValue+"\"");
out.println(" end=\""+monthLong1UI+" "+dayLong1UI+" "+yearLong1UI+" 00:00:00 EST"+"\"");
out.println(" "+descriptionUI);
out.println("");
out.println("</event>");
out.println(" <!-- Above event added by: " +System.getProperty("user.name")+" " +
"on: "+month+"/"+day+"/"+year+" -->");
}catch (IOException e) {
System.err.println(e);
}finally{
if(out != null){
out.close();
}
}
所以最后,我希望它写入一个已经存在的 XML 文件(我可以通过简单地更改编写器的位置来实现)。问题是,这个 XML 文件有一个根标签,称为 <data>
.我需要我的程序的结果放在 XML 文件的底部,但在 </data>
之前。 .这是唯一的要求。我发现的一切似乎都太复杂了,我无法弄明白..
非常感谢任何帮助!
最佳答案
您应该使用合适的 XML API。例如,这是一个使用 JDOM 的示例:
import java.io.*;
import org.jdom2.*;
import org.jdom2.input.*;
import org.jdom2.output.*;
public class Test {
public static void main(String args[]) throws IOException, JDOMException {
File input = new File("input.xml");
Document document = new SAXBuilder().build(input);
Element element = new Element("event");
element.setAttribute("title", "foo");
// etc...
document.getRootElement().addContent(element);
// Java 7 try-with-resources statement; use a try/finally
// block to close the output stream if you're not using Java 7
try(OutputStream out = new FileOutputStream("output.xml")) {
new XMLOutputter().output(document, out);
}
}
}
真的没那么难……而且比手动写出来要稳健得多。 (例如,如果您的事件标题包含“&”,这将执行正确的操作 - 而您的代码会生成无效的 XML。)
关于java - 从 Java 写入 XML 文档 - 简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820779/