繁体   English   中英

附加到XML文档JAXB

[英]Append to XML document JAXB

我已经使用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>

我想使用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>

我知道XML不适合记录数据,但是我必须在项目中使用XML。 我怎样才能做到这一点?

假设存在以下类别

@XmlRootElement
public class Persons{

List<Person> person;

...getters and setters
}

public class Person{
...fields, getters and setters...
}

首先,您将原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);

然后你得到人对象

Persons persons = personsElement.getValue();

接着。 放置您要附加的对象

Person newPerson = new Person();

... put values into newPerson

persons.getPerson().add(newPerson);

最后,您将其编组

Marshaller marshaller = context.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(personsElement, the output Stream to your file);

您也可以在oracle的教程中找到很多示例

https://docs.oracle.com/javaee/5/tutorial/doc/bnbah.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM