3

我正在尝试XMLArrayList<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>

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

谢谢

4

1 回答 1

2

首先,您有一个围绕 xmlWriter 的 for 循环,这就是为什么您有两个 <simulation> 根元素的原因。

于 2013-06-04T18:22:03.007 回答