简体   繁体   中英

How to write the contents of Arraylist to xml file in Java

It's a simple problem. but i am not able to debug it. I have class "Adding.java" that adds some data to 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

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

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?

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.

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())));
}

You need to iterate through your list in increments of 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.

Here is an example of a clear XML file:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM