【问题标题】:Can JAXB Incrementally Marshall An Object?JAXB 可以增量编组对象吗?
【发布时间】:2011-02-01 20:05:16
【问题描述】:

我有一个相当简单但可能很大的结构来序列化。基本上 XML 的结构是:

<simple_wrapper>
   <main_object_type>
     <sub_objects>
   </main_object_type>
     ... main_object_type repeats up to 5,000 times
</simple_wrapper>

main_object_type 可以包含大量数据。在我第一次提取 3,500 条记录时,我不得不为 JVM 提供比它应该需要的更多的内存。

所以,我想在每个(或一堆)main_object_type 之后写入磁盘。

我知道设置 Marshaller.JAXB_FRAGMENT 会允许它碎片化,但我会丢失外部 xml 文档标签和 &lt;simple_wrapper&gt;

有什么建议吗?

【问题讨论】:

    标签: jaxb marshalling


    【解决方案1】:

    下面的呢?

    JAXBContext jaxbContext= JAXBContext.newInstance(MainObjectType.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    
    OutputStreamWriter writer = new OutputStreamWriter(System.out);
    
    // Manually open the root element
    writer.write("<simple_wrapper>");
    
    // Marshal the objects out individually
    marshaller.marshal(mainObjectType1, writer);
    marshaller.marshal(mainObjectType2, writer);
    marshaller.marshal(mainObjectType3, writer);
    marshaller.marshal(mainObjectType4, writer);
    ...
    
    // Manually close the root element
    writer.write("</simple_wrapper>");
    writer.close();
    

    这假设您在 MainObjectType 上有一个 @XmlRootElement

    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class MainObjectType {
        ...
    }
    

    【讨论】:

      【解决方案2】:

      您可以将对象编组为 SAX 或 StAX 流。

      【讨论】:

      • 如果我使用流,为&lt;simple_wrapper&gt; 创建JAXBElement&lt;?&gt; 的标准方法是否仍需要将所有包含的对象保存在内存中?我正在寻找的是如何将其分解,而不必花费大量手动工作来编写 &lt;xml&gt; 标头等。我想打开 &lt;simple_wrapper&gt; 并编写每个 &lt;main_object_type&gt;,因为它们是从中检索到的DB,没有太多的猴子工作。
      • 尝试将@XmlID 与自定义IDResolver 一起使用:weblogs.java.net/blog/2005/08/15/… 您的简单包装器将仅存储对象的ID 并通过ID 解析器检索对象实例。
      猜你喜欢
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多