簡體   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