4

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.!!

Aatif
  • 179
  • 6
  • 15

1 Answers1

2

The XML that you need is not well-formed.

I suggest you to 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

}

output expected

<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 there is a possible solution to append xml into a file.

Community
  • 1
  • 1
Xstian
  • 8,184
  • 10
  • 42
  • 72