2012-07-12 43 views
1

這裏是我的簡單的代碼創建XML文件:例外使用XML輸出器

try 
       { 
        Element performances = new Element("performances"); 
        Document doc = new Document(performances); 
        doc.setRootElement(performances); 

        performances.setAttribute(new Attribute("date", dateFormat.format(cal.getTime()))); 

        Element uptime = new Element("uptime"); 
        uptime.addContent(new Element("days").setText(new Long(duptime).toString())); 
        uptime.addContent(new Element("hours").setText(new Long(huptime).toString())); 
        uptime.addContent(new Element("minutes").setText(new Long(muptime).toString())); 
        uptime.addContent(new Element("seconds").setText(new Long(suptime).toString())); 

        doc.getRootElement().addContent(uptime); 

        XMLOutputter xmlOutput = new XMLOutputter(); 

        xmlOutput.setFormat(Format.getPrettyFormat()); 
        xmlOutput.output(doc, new FileWriter("/homa/mazzy/Scrivania/perfor_"+dateFormat.format(cal.getTime())+"xml")); 

我得到這個例外

Exception in thread "AWT-EventQueue-0" org.jdom2.IllegalAddException: The element "performances" could not be added as the root of the document: The Content already has an existing parent document 

,但我不知道這是什麼means.where是錯誤?

+0

這樣,如果你想第二根元素添加到exicted DOM樹引發的異常。 – 2012-07-12 09:53:24

+0

我的答案能解決你的問題嗎? – 2012-07-12 10:03:40

回答

1

這兩行

Document doc = new Document(performances); 
doc.setRootElement(performances); 

原因的誤差。第一個設置根,第二個再次死亡。

編輯

Document doc = new Document() 
doc.setRootElement(performances) 

Document doc = new Document(performances) 
+0

這兩條線是一樣的嗎? – user1508419 2012-07-12 09:37:19

+0

請參閱http://jdom.org/docs/apidocs/org/jdom2/Document.html#Document%28org.jdom2.Element%29和http://jdom.org/docs/apidocs/org/jdom2/Document。 HTML#setRootElement%28org.jdom2.Element 29% – 2012-07-12 09:38:55