[英]Append to XML document JAXB
I have used JAXB to create an XML file like this: 我已经使用JAXB来创建这样的XML文件:
-<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: 我想使用JAXB附加到此文件,如下所示:
-<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. 我知道XML不适合记录数据,但是我必须在项目中使用XML。 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 首先,您将原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 您也可以在oracle的教程中找到很多示例
https://docs.oracle.com/javaee/5/tutorial/doc/bnbah.html https://docs.oracle.com/javaee/5/tutorial/doc/bnbah.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.