附加到XML文档JAXB

时间:2016-03-11 01:39:43

标签: java xml 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不适合记录数据,但我必须将它用于我的项目。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

假设存在以下类

@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