1

The Method below is supposed to take all the stored students and generate an XML file with the data. As is the XML is structured correctly but both entries are the same. Instead of getting data for student1 and student2 I just get student2 twice in a row. What am I missin here?

public void exportStudentXML(ArrayList <Student> studentListIn ){
    ArrayList <Student> studentList = studentListIn;

    DocumentBuilderFactory myDocBuilderFactory = DocumentBuilderFactory.newInstance();

    try{
        DocumentBuilder myDocBuilder = myDocBuilderFactory.newDocumentBuilder();
        Document documentModel = myDocBuilder.newDocument();

        Element root = documentModel.createElement("studentList");
        documentModel.appendChild(root);

        for (Student thisStudent : studentList){
            Element listElement = documentModel.createElement("student");
            root.appendChild(listElement);

            Element nameElement = documentModel.createElement("name");
            Text nameText = documentModel.createTextNode(thisStudent.name);
            nameElement.appendChild(nameText);
            listElement.appendChild(nameElement);

            Element addressElement = documentModel.createElement("address");
            Text addressText = documentModel.createTextNode(thisStudent.address);
            addressElement.appendChild(addressText);
            listElement.appendChild(addressElement);

            Element ssnElement = documentModel.createElement("ssn");
            Text ssnText = documentModel.createTextNode(thisStudent.socialSecurityNumber);
            ssnElement.appendChild(ssnText);
            listElement.appendChild(ssnElement);

            Element dobElement = documentModel.createElement("dob");
            Text dobText = documentModel.createTextNode(thisStudent.toStringDOB());
            dobElement.appendChild(dobText);
            listElement.appendChild(dobElement);

            Element dogElement = documentModel.createElement("dog");
            Text dogText = documentModel.createTextNode(thisStudent.toStringDOG());
            dogElement.appendChild(dogText);
            listElement.appendChild(dogElement);

            Element gpaElement = documentModel.createElement("gpa");
            Text gpaText = documentModel.createTextNode(thisStudent.toStringGPA());
            gpaElement.appendChild(gpaText);
            listElement.appendChild(gpaElement);

        }
        OutputFormat formatToOutput = new OutputFormat(documentModel);

        formatToOutput.setIndenting(true);
        XMLSerializer serializer = new XMLSerializer( new FileOutputStream( new File("studentlist.xml")), formatToOutput );
        serializer.serialize(documentModel);

    }catch(Exception e){



    }      

}
1
  • 1
    Can you provide the code from where you are calling this method? Where you add the students to the studentList? Commented Jul 22, 2015 at 17:18

1 Answer 1

2

This code works fine, the problem is in the code that you didn't show us: class Student - you declared all the fields there as static which means there's only one copy and when you create "multiple students" each new student overrides the values of the previous one.

Remove the static keyword before all the members in class Student (name, address and etc) and your code will work. Here's a working example with a few minor modifications of your code:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

class StudentsToXML {

    public static void main(String[] args) {
        ArrayList <Student> studentList = new ArrayList<>();
        studentList.add(new Student("John", "CA", "123"));
        studentList.add(new Student("Mark", "AZ", "456"));
        exportStudentXML(studentList);    
    }

    public static void exportStudentXML(ArrayList <Student> studentList ){
        DocumentBuilderFactory myDocBuilderFactory = DocumentBuilderFactory.newInstance();

        try{
            DocumentBuilder myDocBuilder = myDocBuilderFactory.newDocumentBuilder();
            Document documentModel = myDocBuilder.newDocument();

            Element root = documentModel.createElement("studentList");
            documentModel.appendChild(root);

            for (Student thisStudent : studentList){
                Element listElement = documentModel.createElement("student");
                root.appendChild(listElement);

                Element nameElement = documentModel.createElement("name");
                nameElement.appendChild(documentModel.createTextNode(thisStudent.name));
                listElement.appendChild(nameElement);

                Element addressElement = documentModel.createElement("address");
                addressElement.appendChild(documentModel.createTextNode(thisStudent.address));
                listElement.appendChild(addressElement);

                Element ssnElement = documentModel.createElement("ssn");
                ssnElement.appendChild(documentModel.createTextNode(thisStudent.socialSecurityNumber));
                listElement.appendChild(ssnElement);

            }
            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(documentModel);
            StreamResult result = new StreamResult(new File("studentlist.xml"));

            transformer.transform(source, result);    
            System.out.println("File saved!");

        }catch(Exception e){
            e.printStackTrace()
        }
    }
}


class Student {

    Student (String name, String addr, String soc) {
        this.name = name;
        address = addr;
        socialSecurityNumber = soc;
    }
    static String name = "";
    static String address = "";
    static String socialSecurityNumber = "";

}

OUTPUT file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<studentList>
    <student><name>John</name><address>CA</address><ssn>123</ssn></student>
    <student><name>Mark</name><address>AZ</address><ssn>456</ssn></student>
</studentList>
Sign up to request clarification or add additional context in comments.

8 Comments

The variables that are part of student are not static so Im pretty sure that is not it. Also I have another method that displays the contents of studentlist without issue.I figured my issue was how I used the for loop or what I have less familiarity with the XML serializer and the document methods.
@RobMcNeil if it's not that, then it's how you're constructing studentList (adding the same student). The fault is not in the for loop or with the XML construction, as I wrote - this works just fine.
Ill have to look at the changes you made. Im not sure what the difference in what I wrote using DocumentBuilderFactory/Document/DocumentBuilder/OutputFormat/OutputFormat/XMLSerializer and what you wrote using DocumentBuilderFactory/ Document/DocumentBuilder/ TransformerFactory/ Transformer/ DOMSource/ StreamResult Your approach seems a bit different.
@RobMcNeil this change was just made to write the output file, it has nothing to do with your issue.
you were right in that my code worked correctly.I did find an error farther back in where I was not creating a new instance for each student I added and was using the same one for all so the array referenced all the same student multiple times. Thank you for pointing me in the correct direction.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.