2011-11-09 40 views
1

假设我有一个xml文件,其中有几个节点&孩子。我正在使用jaxb(取消编组&编组)在需要时更新xml文件,但想知道什么时候会发生什么.....?编组xml文件时究竟发生了什么

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

现在我想通过增加<node>xyz</node>更新此XML,所以我做了什么

  1. Unmaeshall这个XML文件的Java对象,并添加这个新的节点作为Java对象。

  2. Marshall更新的对象到XML文件。

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

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

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

回答

1

如果您严格谈论File对象,则answer given by Bozho是正确的。如果考虑DOM表示,则JAXB提供了这两种方法:

的Unmarshaller /的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节点之间。如果修改解组对象,则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); 

更多信息

+1

感谢Doughan,我通过你的博客去了,这是一流的。我刚刚通过研究你的博客解决了这个问题。非常感谢。是的,Bozho也是对的。 – user1010399

2

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

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