从Java写入XML文档 - 简单 [英] Writing from Java to an XML document - Simple
问题描述
我知道在stackoverflow上从Java写到XML有很多问题,但它太复杂了。我觉得我有一个非常简单的问题,我无法理解。
I know there's tons of questions on writing from Java to XML on stackoverflow, but it's all too complex. I feel I have a very simple problem that I just can't figure out.
所以我有一个程序需要大量的用户输入,我现在正在创建它并附上包含结果的文本文档。我将在这里发布我的编写器代码:
So I have a program that takes a bunch of user input and I have it currently creating and appending a text document with the results. I'll just post my writer code here:
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>
。这是唯一的要求。我发现的一切看起来都太复杂了,我无法弄清楚..
So in the end, I want it to write to an already existing XML file (which I can do by simply changing where my writer goes to). Problem is, this XML file has ONE root tag known as <data>
. I need the results of my program to go on the bottom of the XML file, but come BEFORE </data>
. That's the only requirement. Everything I find seems too complex and I can't figure it out..
非常感谢任何帮助!
推荐答案
您应该使用一个不错的XML API。例如,以下是使用 JDOM 的示例:
You should use a decent XML API. For example, here's an example using 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);
}
}
}
/ em>并不那么难......它会比手动写出更强大,更强大。 (例如,如果您的事件标题包含&,这将做正确的事情 - 而您的代码会产生无效的XML。)
It's really not that hard... and it'll be much, much more robust than writing it out manually. (For example, this will do the right thing if your event title contains "&" - whereas your code would have produced invalid XML.)
这篇关于从Java写入XML文档 - 简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!