【问题标题】:what exactly happens when marshalling the xml file编组 xml 文件时究竟发生了什么
【发布时间】:2011-11-09 17:58:49
【问题描述】:

假设我有一个包含多个节点和子节点的 xml 文件。我正在使用 jaxb (unmarshalling & marshalling) 在需要时更新 xml 文件,但想知道什么时候发生...... ??

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

现在我想通过添加&lt;node&gt;xyz&lt;/node&gt; 来更新这个xml,所以我该怎么做

  1. 将此 xml 文件取消映射到 java 对象并将此新节点添加为 java 对象。

  2. 将更新的对象编组为 XML 文件。

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

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

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

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      解组器/编组器

      在以下代码中 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。当文档中存在需要保留的未映射内容(如 cmets 和处理指令)时,这种方法非常有用。

          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);
      

      更多信息

      【讨论】:

      • 谢谢 Doughan,我浏览了你的博客,非常棒。我刚刚通过研究你的博客自己解决了这个问题。多谢。是的,博卓也是对的。
      猜你喜欢
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      相关资源
      最近更新 更多