I am in a situation in my project to marshal a pojo object and writing first time the output into an XMLfile and then appending the same marshaled object with different values but 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' in Person constructor gets change and next time the Person object gets marshaled with different property values the 'file.xml' file is overwritten and i lost the previous output. Simply i want to append the marshaled Person object every time when 'id' get's changed. i.e the 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 hint me how to do this. Any help is appreciated. I tried to search the similar scenario on stackoverflow Q/A list but couldn't find.
Warm Regards.!!