JAXB如何推进XMLStreamReader? [英] How does JAXB advance the XMLStreamReader?

查看:111
本文介绍了JAXB如何推进XMLStreamReader?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JAXB使用XMLStreamReader从非常大的XML文件解组对象。

I'm using JAXB to unmarshal objects from very large XML files using an XMLStreamReader.

如果我解组的XML元素是分开的(通过换行符或单个空格),这可以正常工作。

If the XML elements I'm unmarshalling are separated (by a newline or even a single space) this works fine.

如果我解组的XML元素之间没有空格,我就会丢失所有其他项目 - XML阅读器似乎会在取消编组之后吞下该元素。

If the XML elements I'm unmarshalling do not have whitespace between them, I lose every other item - the XML reader seems to swallow the element after the one that gets unmarshalled.

一个简化的可运行示例的源代码,用于演示这是 https://gist.github.com/dalelane/88df784c3cb74b214d5c

Source for a simplified runnable example that demonstrates this is at https://gist.github.com/dalelane/88df784c3cb74b214d5c

有趣的是:

XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
JAXBContext context = JAXBContext.newInstance(MyJAXBClass.class);
Unmarshaller unmarshaller = context.createUnmarshaller();

boolean running = true;
while (running){
    switch (reader.next()){
        case XMLStreamConstants.START_ELEMENT:
            if (reader.getLocalName().equals("myunmarshallobjname")){
                JAXBElement<MyJAXBClass> unmarshalledObj = unmarshaller.unmarshal(reader, MyJAXBClass.class);
                MyJAXBClass item = unmarshalledObj.getValue();
            }
            break;
        case XMLStreamConstants.END_DOCUMENT:
            reader.close();
            running = false;
            break;
    }
}

每次流阅读器点击元素的开头,我将它传递给unmarshaller来解组那个片段。

Every time the stream reader hits the start of an element, I pass it to the unmarshaller to unmarshall that fragment.

如果我的XML包含:

<myunmarshallobjname key="one"></myunmarshallobjname> <myunmarshallobjname key="two"></myunmarshallobjname>

但如果我有以下物品则会丢失物品:

But loses items if I have:

<myunmarshallobjname key="one"></myunmarshallobjname><myunmarshallobjname key="two"></myunmarshallobjname>

我做错了什么?如何让读者不要跳过元素?

What am I doing wrong? How do I get the reader to not skip over elements?

推荐答案

仔细检查解组调用后您所在的元素事件。如果 XMLStreamReader endElement 上,则需要调用 next()作为循环的一部分,但它在 startElement 你不会。

Double check which element event you are on after the unmarshal call. If the XMLStreamReader is on endElement you will need to call next() as part of your loop, but it's on startElement you won't.

这篇关于JAXB如何推进XMLStreamReader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆