繁体   English   中英

编组xml文件时到底发生了什么

[英]what exactly happens when marshalling the xml file

假设我有一个具有多个节点和子节点的xml文件。 我在需要时使用jaxb(解组和编组)更新xml文件,但想知道什么时候会发生什么.....?

<parent>
    <node>abc</node>
</parent>

现在我想通过添加<node>xyz</node>来更新此xml,所以我该怎么做

  1. 将此XML文件取消编组为java对象,并将此新节点添加为java对象。

  2. Marshall更新的Object to XML文件。

我的问题是:将Java对象编组为xml文件时会发生什么?

选项a)xml文件删除所有内容并重新编写。

选项b)仅通过添加新行来更新xml文件。

默认情况下,内容被覆盖。

仅当您使用m.marshal(jaxbObj, new FileOutputStream(file, true)) (append = true)时,才会追加新内容。

如果严格讲File对象,那么Bozho给出的答案是正确的。 如果考虑DOM表示,那么JAXB提供两种方法:

解组/的Marshaller

在以下代码中originalDOM!= marshalledDOM。

Node originalDOM;  // Populate original document

JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(orginalDocument);

Marshaller marshaller = jc.createMarshaller();
marshalledDOM = marshaller.getNode(customer);

活页夹

当使用Binder ,在对象和DOM节点之间保持链接,它们是从中解组的。 如果修改了unmarshalled对象, Binder会将这些更改应用回原始DOM。 当您需要保留文档中未映射的内容(例如注释和处理说明)时,此方法非常有用。

    JAXBContext jc = JAXBContext.newInstance(Customer.class);

    Binder<Node> binder = jc.createBinder();
    Customer customer = (Customer) binder.unmarshal(document);
    customer.getAddress().setStreet("2 NEW STREET");
    binder.updateXML(customer);

欲获得更多信息

暂无
暂无

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

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