I have used JAXB to create an XML file like this:
-<persons>
-<person>
<active>Active</active>
<amountOwed>500 Galleons</amountOwed>
<email>harrypotter@hogwarts.edu</email>
<firstName>harry</firstName>
<lastName>potter</lastName>
<memberNum>1234</memberNum>
<school>Hogwarts</school>
<state>some state</state>
<yearJoined>1991</yearJoined>
</person>
</persons>
I would like to use JAXB to append to this file like this:
-<persons>
-<person>
<active>Active</active>
<amountOwed>500 Galleons</amountOwed>
<email>harrypotter@hogwarts.edu</email>
<firstName>harry</firstName>
<lastName>potter</lastName>
<memberNum>1234</memberNum>
<school>Hogwarts</school>
<state>some state</state>
<yearJoined>1991</yearJoined>
</person>
<person>
<active>Inactive</active>
<amountOwed>123412362 Galleons</amountOwed>
<email>ronweasley@hogwarts.edu</email>
<firstName>ron</firstName>
<lastName>weasley</lastName>
<memberNum>2342</memberNum>
<school>hogwarts</school>
<state>some state</state>
<yearJoined>1991</yearJoined>
</person>
</persons>
I know XML is not a good fit for logging data, but I must use it for my project. How can I do this?
assuming the following class exists
@XmlRootElement
public class Persons{
List<Person> person;
...getters and setters
}
.
public class Person{
...fields, getters and setters...
}
first you unmarshal the origin xml
JAXBContext context = JAXBContext.newInstance(Persons.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File f = new File("the original xml");
JAXBElement<Persons> personsElement = (JAXBElement<Persons>) unmarshaller.unmarshal(f);
and then you get the persons object
Persons persons = personsElement.getValue();
and then. put the object that you want to append
Person newPerson = new Person();
... put values into newPerson
persons.getPerson().add(newPerson);
last, you marshal it
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(personsElement, the output Stream to your file);
You can also find a lot of example in oracle's tutorial
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.