如何在Java中将Arraylist的内容写入xml文件

时间:2012-04-19 11:24:52

标签: java xml 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);

    } }

和另一个创建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”元素有问题吗? 。任何帮助表示赞赏。提前致谢

3 个答案:

答案 0 :(得分:2)

为什么不在列表中存储学生对象,每个对象都有姓名,身份证和年龄?这将更易于维护,并且易于编程?

目前,您使用列表中的相同索引来查找三个属性。你需要在循环中迭代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())));
}

答案 1 :(得分:1)

您需要以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);

    }

但是,您可能最好存储在自定义类的列表对象中,并使用专用字段表示名称,ID和年龄。

答案 2 :(得分:0)

以下是一个清晰的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);

}

,结果如下:

<?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>

因此,您可以添加学生的信息,而不是矩形。