Philip Morris
Philip Morris

Reputation: 469

How to write multiple XML root elements using JAXB

I have this code for writing Java objects to XML

public void convToXML(SampleClass sample,File file){

          try {

            JAXBContext jaxbContext = JAXBContext.newInstance(SampleClass .class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();


            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(trans, file);
            jaxbMarshaller.marshal(trans, System.out);

              } catch (JAXBException e) {
            e.printStackTrace();
              }

        }

I also have a system of producing objects in a loop but this method only prints the latest object in the XML file. How do I make it that it will print XML root elements sequentially and not write a new one everytime?

I cal this method after adding attributes to the object inside a loop

while(condition){
SampleClass sample = new SampleClass();
sample.setName("Sample");
sample.setId("432");
convToXML(sample)
}

My System.out is displaying the correct number of XML objects while the file is displaying only the latest. Why is this? The marshall calls are together. . . .

Upvotes: 1

Views: 614

Answers (1)

Santhosh Kumar Tekuri
Santhosh Kumar Tekuri

Reputation: 3020

ensure that file does not exist before starting the loop;

for marshaller, give FileOutputStream with append enabled;

here is the working code for you problem:

File file = ...;

public void convToXML(SampleClass sample, File file){
    try{
        JAXBContext jaxbContext = JAXBContext.newInstance(SampleClass.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(trans, new FileOutputStream(file, true));
        jaxbMarshaller.marshal(trans, System.out);

    }catch(JAXBException e){
        e.printStackTrace();
    }
}

file.delete();
while(condition){
    SampleClass sample = new SampleClass();
    sample.setName("Sample");
    sample.setId("432");
    convToXML(sample, file)
}    

Upvotes: 1

Related Questions