我正在尝试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>
我做错了什么,如何解决它以获得预期的输出?
谢谢