从ArrayList写入XML文件 - 输出错误

时间:2013-06-04 18:13:48

标签: java xml arraylist

我正在尝试从XML写一个ArrayList<Element>文件。但是,输出不是我的预期,我似乎无法找出问题的根源。你能帮我吗?

以下是我的一些代码:

    if (e.getSource() == saveMenu) {
        writeToXML();
        JOptionPane.showMessageDialog(Simulation.this, 
                    "File saved", 
                    "Simulation", JOptionPane.INFORMATION_MESSAGE);

    }

 public void writeToXML() throws IOException {

     int size = alElementToXML.size();
     for (int i = 0; i < size; i++) {
         alIds.add(alElementToXML.get(i).attributeValue("id"));
     }

     OutputFormat format = OutputFormat.createPrettyPrint();
     format.setEncoding("UTF-8");
     XMLWriter xmlWriter = null;
     xmlWriter = new XMLWriter(new OutputStreamWriter(
             new FileOutputStream("Simulation_" + MASG_GUI.getContainerNameTxt().getText() + "_Details.xml"), "UTF8"),
             format);
     try {
         for (int i = 0; i < size; i++) {
             xmlWriter.write(configs.XMLwriterDOM4J.createXMLDocumentForSimulations(alElementToXML, alIds.get(i)));
         }
     } finally {

         xmlWriter.flush();
         xmlWriter.close();
     }
 }

这是createXMLDocumentForSimulations方法:

public static Document createXMLDocumentForSimulations(ArrayList<Element> elems, String id) {

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("simulation");
    Element agent1 = root.addElement("member").addAttribute("id", id);
    int size = Simulation.getAlElementToXML().size();
    for (int i = 0; i < size; i++) {           
         agent1.addElement(elems.get(i).asXML());
    }
    return document;
}

和我得到的输出的一个例子:

<?xml version="1.0" encoding="UTF-8"?>

<simulation>
  <member id="House">
    <<member id="House"><id>1</id><type>1</type><max_usage>1</max_usage><min_usage>1</min_usage><average_usage>1</average_usage></member>/>
    <<member id="CSP"><id>1</id><type>1</type></member>/>
    <<member id="VPP"><id>6</id><type>6</type></member>/>
  </member>
</simulation>
<?xml version="1.0" encoding="UTF-8"?>

<simulation>
  <member id="CSP">
    <<member id="House"><id>1</id><type>1</type><max_usage>1</max_usage><min_usage>1</min_usage><average_usage>1</average_usage></member>/>
    <<member id="CSP"><id>1</id><type>1</type></member>/>
    <<member id="VPP"><id>6</id><type>6</type></member>/>
  </member>
</simulation>

我想要的是这样的:

<?xml version="1.0" encoding="UTF-8"?>

<simulation>
  <member id="House">
    <id>1</id>
    <type>1</type>
    <max_usage>1</max_usage>
    <min_usage>1</min_usage>
    <average_usage>1</average_usage>
  </member>
  <member id="VPP">
    <id>6</id>
    <type>6</type>
  </member>
</simulation>

我做错了什么以及如何解决它以获得预期的输出?

由于

1 个答案:

答案 0 :(得分:2)

首先,你的xmlWriter周围有一个for循环,这就是为什么你有两个&lt; simulation&gt;根元素。