从 Java 写入 XML 文档 - 简单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15820779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing from Java to an XML document - Simple
提问by user2221125
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.
我知道在 stackoverflow 上有很多关于从 Java 写入 XML 的问题,但这太复杂了。我觉得我有一个非常简单的问题,我就是想不通。
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();
}
}
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 文件(我可以通过简单地改变我的作者去哪里来做到这一点)。问题是,这个 XML 文件有一个根标记,称为<data>
. 我需要将程序的结果放在 XML 文件的底部,但要在</data>
. 这是唯一的要求。我发现的一切似乎都太复杂了,我无法弄清楚..
Any help is very much appreciated!
很感谢任何形式的帮助!
回答by Jon Skeet
You should use a decent XML API. For example, here's an example using JDOM:
您应该使用一个不错的 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);
}
}
}
It's reallynot 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.)
这真的没有那么难......而且它会比手动写出更强大。(例如,如果您的事件标题包含“&”,这将是正确的——而您的代码会产生无效的 XML。)
回答by MariuszS
If you like fluent api, then you can use JOOX:
如果你喜欢fluent api,那么你可以使用JOOX:
File file = new File("projects.xml");
Document document = $(file).document();
Comment eventComment = document.createComment("Above event added by: "
+ System.getProperty("user.name") + "\n" +
" on: " + month + "/" + day + "/" + year);
document = $(file)
.xpath("//data")
.append($("event",
$("title", "titleFieldUI"),
$("start", monthLongUI + " " + dayLongUI + " " + yearLongUI + " 00:00:00 EST"),
$("isDuration", "true"),
$("color", sValue),
$("end", monthLong1UI + " " + dayLong1UI + " " + yearLong1UI + " 00:00:00 EST")))
.append($(eventComment))
.document();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(file);
Source input = new DOMSource(document);
transformer.transform(input, output);
or XMLBuilder
XMLBuilder builder = XMLBuilder.parse(
new InputSource(new FileReader("C:/Documents and Settings/blank/My Documents/test/test.txt")))
.xpathFind("//data")
.e("event")
.a("title", titleFieldUI)
.a("start", monthLongUI + " " + dayLongUI + " " + yearLongUI + " 00:00:00 EST")
.a("isDuration", "true")
.a("color", sValue)
.a("end", monthLong1UI + " " + dayLong1UI + " " + yearLong1UI + " 00:00:00 EST")
.up()
.comment("Above event added by: " + System.getProperty("user.name") + "\n" +
" on: " + month + "/" + day + "/" + year);
PrintWriter writer = new PrintWriter(new FileOutputStream("C:/Documents and Settings/blank/My Documents/test/test.txt"));
builder.toWriter(writer, new Properties());
回答by Vlad Topala
You could use JOOX. This is how you would do an append:
你可以使用JOOX。这是您执行追加的方式:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse("/pathToXML");
JOOX.$(doc).append("<newNode>data<newNode>");
By default the $(doc) will load the root node. If you want an inner node you can use the find() method. The library is not documented very well but being open source you can always directly check the sources.
默认情况下, $(doc) 将加载根节点。如果你想要一个内部节点,你可以使用 find() 方法。该库没有很好的文档记录,但作为开源,您可以随时直接检查源代码。