xml - 使用 JAXB 进行部分解码

标签 xml binding jaxb xjc

我想对大型 XML 进行部分解码。

XML 具有以下结构:

<Records>
    <Contract>
        ...
    </Contract>
    <Contract>
        ...
    </Contract>
    ...
    <Contract>
        ...
    </Contract>
    <Contract>
        ...
    </Contract>
</Records>

以及使用 XJC 生成的结果类:

- Records
    |- Contract

如果我关注these (来自 jaxb-ri 的示例),我得到错误:

Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"http://somedomain.com", local:"Contract"). Expected elements are <{http://somedomain.com}Records>

如果我使用:

<jaxb:globalBindings localScoping="toplevel"/>

我得到错误:

org.xml.sax.SAXParseException: A class/interface with the same name "com.my.package.Text" is already in use. Use a class customization to resolve this conflict.

但是我需要改变很多类(class)。这不是解决方案。

最佳答案

/**
 * User: r.ibragimov
 * Date: 04.06.13
 */
public class PartialJAXB1 {

    public static void main(String[] args) throws JAXBException, XMLStreamException, FileNotFoundException {

        final QName qName = new QName("http://www.domain.com","Contract");

        InputStream inputStream = new FileInputStream(new File("c:\\test.xml"));

        // create xml event reader for input stream
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(inputStream);

        // initialize jaxb
        JAXBContext context = JAXBContext.newInstance(Records.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        XMLEvent e = null;

        // loop though the xml stream
        while( (e = xmlEventReader.peek()) != null ) {

            // check the event is a Document start element
            if(e.isStartElement() && ((StartElement)e).getName().equals(qName)) {

                // unmarshall the document
                Records.Contract contract = unmarshaller.unmarshal(xmlEventReader, Records.Contract.class).getValue();
                System.out.println(contract);
            } else {
                xmlEventReader.next();
            }

        }

    }
}

关于xml - 使用 JAXB 进行部分解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16914628/

相关文章:

java - 使用 JaxB 编码实现公共(public)接口(interface)的对象列表

java - 实体的 jaxb XML Marshall 中的 dbId ="0"

java - 如何修复此错误 AAPT2 错误 : check logs for details?

xml - 修剪 XSLT 中字符后的字符串

c# - 有没有办法刷新 WPF 中的所有绑定(bind)?

java - 如果抛出异常,如何防止 XML 文件内容被修改

c# - Xsd.exe 或 Svcutil.exe 将 XSD 架构转换为类

wpf - 模板绑定(bind)到背景和前景色?

WPF 数据网格 : Get column binding property for filtering

java - 如何通过 JAXB 注释类序列化此 JSON 格式?