Add Marshalled Object to XML file using JAXB

In my project I am planning to marshal a pojo object and write the output to an XML file first, then add the same marshaled object with different values, but the same node and child nodes in the same file. Here is the following code -

 **Person person = new Person(personList.get(id));**
    try {
        File file = new File("D:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

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

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

   Output:

     file.xml created with bellow structure -

     <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     <person>
       <country>India</country>
       <id>1</id>
       <name>Aatif Hasan</name>
     </person>

      

As the "id" constructor in Person gets changed, and the next time the Person object gets marshaled with different property values, the "file.xml" file gets overwritten and I lost the previous output. I just want to add a marshaled Person object every time the "id" is changed. those. object properties are set with different values. Ex ..

     <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     <person>
       <country>India</country>
       <id>1</id>
       <name>Aatif Hasan</name>
     </person>
     <person>
       <country>USA</country>
       <id>2</id>
       <name>ABC</name>
     </person>
     <person>
       <country>UK/country>
       <id>3</id>
       <name>XYZ</name>
     </person>
         .
         .
         .
    and so on..

      

Please, any body will tell me how to do this. Any help is appreciated. I tried searching for a similar scenario in the Q / A list for stackoverflow but couldn't find it.

Warm greetings. !!

+3


source to share


1 answer


The XML you need is not valid.

I suggest you wrap all Person.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Persons", propOrder = {
    "person"
})
@XmlRootElement(name = "Persons")
public class Persons
    implements Serializable
{

    private final static long serialVersionUID = 12343L;
    @XmlElement(name = "Person", required = true)
    protected List<Person> person;

    // getter and setter

}

      



Expected Result

<persons>
    <person>
       <country>India</country>
       <id>1</id>
       <name>Aatif Hasan</name>
    </person>
    <person>
       <country>USA</country>
       <id>2</id>
       <name>ABC</name>
    </person>
    <person>
       <country>UK/country>
       <id>3</id>
       <name>XYZ</name>
    </person>
</persons>

      

Anything here is a possible solution for adding xml to the file.

+2


source







All Articles