使用xml outputter创建xml文件时出现异常

时间:2012-07-12 09:33:19

标签: java 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

但我不知道这意味着什么。错误在哪里?

1 个答案:

答案 0 :(得分:1)

这两行

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

导致错误。第一个设置根,第二个再次设置它。

修改

待办事项

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

Document doc = new Document(performances)