2013-04-04 52 views
3

我知道在stackoverflow上从Java写入XML有很多问题,但这太复杂了。我觉得我有一个非常简单的问题,我无法弄清楚。从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>之前。这是唯一的要求。我发现的一切似乎太复杂,我不知道它..

任何帮助非常感谢!

回答

5

你应该使用一个体面的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。)

+0

如何在JDOM中添加对XML文档的评论? – MariuszS 2013-04-04 20:59:07

+3

@MariuszS:我不知道,所以我查看了文档。它并没有耗费我很长时间,我相信它不会让你长时间:) – 2013-04-04 21:00:47

+0

好的,谢谢你的回答:D – MariuszS 2013-04-04 21:05:47

2

如果你喜欢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); 

或​​

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()); 
+0

这并不真正显示如何追加数据,对吧? – 2013-04-04 20:16:20

+0

这不会帮助我,因为我不想创建XML文件。 XML文件已经存在,我需要在它的GUI程序中输入信息。 – user2221125 2013-04-04 20:16:50

+0

你太快了:)这并没有完成:D – MariuszS 2013-04-04 20:22:05

0

您可以使用JOOX。这是你如何做一个追加:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder parser = factory.newDocumentBuilder(); 
Document doc = parser.parse("/pathToXML"); 

JOOX.$(doc).append("<newNode>data<newNode>"); 

默认情况下$(doc)将加载根节点。如果你想要一个内部节点,你可以使用find()方法。该库没有很好地记录,但作为开放源代码,您始终可以直接查看源代码。

+0

您可以使用如下代码创建文档:$(new File(“/ pathToXML”))。document(); – MariuszS 2013-04-06 14:50:28