2013-04-04 43 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