java Java如何将Arraylist的内容写入xml文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10226998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write the contents of Arraylist to xml file in Java
提问by user745475
It's a simple problem. but i am not able to debug it. I have class "Adding.java" that adds some data to ArrayList
这是一个简单的问题。但我无法调试它。我有类“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);
} }
and another class "WriteFile.java" that creates a xml file
和另一个创建 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");
}
when i execute this i get following output
当我执行这个我得到以下输出
<?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>
and so on. But I want the final output to be of this form
等等。但我希望最终输出是这种形式
<?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>
Is there any problem with "for" loop to iterate over "list" element ?? . Any help is appreciated. Thanks in advance
“for”循环迭代“list”元素有什么问题吗??. 任何帮助表示赞赏。提前致谢
回答by JB Nizet
Why don't you store Student objects in your list, each having a name, an ID and an age? This would be much more maintainable, and easy to program?
为什么不将 Student 对象存储在列表中,每个对象都有名称、ID 和年龄?这会更易于维护,并且易于编程?
At the moment, you use the same index in the list to find the three properties. You would need to iterate by steps of 3 in the loop, and get the elements i, i+1 and i+2 to make it work.
目前,您使用列表中的相同索引来查找三个属性。您需要在循环中按 3 步进行迭代,并获取元素 i、i+1 和 i+2 以使其工作。
list.add(new Student("Tim", 2333, 23));
list.add(new Student("John", 423, 23));
...
for (Student student : studentList) {
...
name.appendChild(doc.createTextNode(student.getName()));
...
id.appendChild(doc.createTextNode(Integer.toString(student.getId())));
...
age.appendChild(doc.createTextNode(Integer.toString(student.getAge())));
}
回答by Péter T?r?k
You need to iterate through your list in increments of 3:
您需要以 3 为增量迭代您的列表:
for(int i=0; i<list.size() - 2; i += 3 ) {
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 + 1))));
Details.appendChild(id);
Element mmi = doc.createElement("Age");
mmi.appendChild(doc.createTextNode(String.valueOf(list.get(i + 2))));
Details.appendChild(mmi);
}
But you would probably be better off storing in your list objects of a custom class, with dedicated fields for name, id and age.
但是您可能最好将自定义类的列表对象存储在列表中,并带有用于名称、ID 和年龄的专用字段。
回答by Sandra Sukarieh
Here is an example of a clear XML file:
这是一个清晰的 XML 文件的示例:
Element root = doc.createElement("RectanglesInfo");
doc.appendChild(root);
for(int i=0; i<rectangles.size(); i ++ ) {
Element rectangle = doc.createElement("Rectangle");
root.appendChild(rectangle);
Element width = doc.createElement("width");
width.appendChild(doc.createTextNode(Double.toString(rectangles.get(i).getWidth())));
rectangle.appendChild(width);
Element height = doc.createElement("height");
height.appendChild(doc.createTextNode(Double.toString(rectangles.get(i).getHeight())));
rectangle.appendChild(height);
}
and the result will be like this:
结果将是这样的:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<RectanglesInfo>
<Rectangle>
<width>89.0</width>
<height>85.0</height>
</Rectangle>
<Rectangle>
<width>205.0</width>
<height>212.0</height>
</Rectangle>
</RectanglesInfo>
So instead of rectangles you can add the info of your students.
因此,您可以添加学生的信息而不是矩形。