这是一个简单的问题。但我无法调试它。我有类“Adding.java”,它向 ArrayList 添加了一些数据
public class Adding {
WriteFile ob = new WriteFile();
ArrayList list = new ArrayList();
public void add(){
list.add("Tim");
list.add(2333);
list.add(23);
list.add("John");
list.add(423);
list.add(23);
ob.writeXmlFile(list);
} }
和另一个创建 xml 文件的类“WriteFile.java”
public class WriteFile {
public void writeXmlFile(ArrayList<Object> list) {
try {
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
Element root = doc.createElement("Studentinfo");
doc.appendChild(root);
Element Details = doc.createElement("Details");
root.appendChild(Details);
for(int i=0; i<list.size(); i ++ ) {
Element name = doc.createElement("Name");
name.appendChild(doc.createTextNode(String.valueOf(list.get(i))));
Details.appendChild(name);
Element id = doc.createElement("ID");
id.appendChild(doc.createTextNode(String.valueOf(list.get(i))));
Details.appendChild(id);
Element mmi = doc.createElement("Age");
mmi.appendChild(doc.createTextNode(String.valueOf(list.get(i))));
Details.appendChild(mmi);
}
// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
// format the XML nicely
aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
aTransformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
try {
FileWriter fos = new FileWriter("/home/ros.xml");
StreamResult result = new StreamResult(fos);
aTransformer.transform(source, result);
} catch (IOException e) {
e.printStackTrace();
}
} catch (TransformerException ex) {
System.out.println("Error outputting document");
} catch (ParserConfigurationException ex) {
System.out.println("Error building document");
}
当我执行此操作时,我得到以下输出
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Studentinfo>
<Details>
<name>Tim</name>
<Id>Tim</Id>
<age>Tim</age>
<name>2333</name>
<Id>2333</Id>
<age>2333</age>
.....
</Details>
</studentinfo>
等等。但我希望最终输出是这种形式
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Studentinfo>
<Details>
<name>Tim</name>
<Id>2333</Id>
<age>23</age>
<name>John</name>
<Id>423</Id>
<age>2333</age>
<size>23</size>
</Details>
</studentinfo>
“for”循环遍历“list”元素有什么问题吗?. 任何帮助表示赞赏。提前致谢