JAXB 从同一个 XML 解组到两个不同的对象

JAXB Unmarshalling to two different objects from same XML

在使用 JAXB 解组的过程中,我试图将 file.xml 解组为 2 个不同的 java pojo,但是解组器一直认为第二个对象仍然是第一个对象,所以它得到一个转换 class 错误。

正如您在下面的代码中看到的那样,我尝试解组

this.timbre = (TimbreFiscalDigital) jaxbUnmarshaller.unmarshal(path.toFile());
this.comprobante = (Comprobante) jaxbUnmarshaller.unmarshal(path.toFile());

它总是得到一个错误,提示存在 class 转换异常

java.lang.ClassCastException: cfdi.bindings.CFDI32.Comprobante cannot be cast to cfdi.bindings.TimbreFiscal.TimbreFiscalDigital

如果我只尝试解组为 "Comprobante" 它可以工作...但不适用于 "TimbreFiscalDigital"

public CFDI(Path path){

     JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance("cfdi.bindings.CFDI32:cfdi.bindings.TimbreFiscal");
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        this.timbre = (TimbreFiscalDigital) jaxbUnmarshaller.unmarshal(path.toFile());
        this.comprobante = (Comprobante) jaxbUnmarshaller.unmarshal(path.toFile());

    } catch (JAXBException ex) {
        Logger.getLogger(CFDI.class.getName()).log(Level.SEVERE, null, ex);
    }    

}

我找不到错误...仅供参考,我使用的是 netbeans 8.1 JAXB

更新 来自评论的示例 XML:

<Comprobante>
    <Emisor></Emisor>
    <Complemento>
        <TimbreFiscalDigital>
        </TimbreFiscalDigital>
    </Complemento>
</Comprobante>

由于您的 XML 包含 <Comprobante> 根元素,因此 XML 将被解组为 Comprobante class 的一个实例。 <Complemento><TimbreFiscalDigital> 嵌套元素将被解组为 Comprobante class.

的嵌套对象

不知道您的架构,我假设 <Complemento> 映射到 Comprobante class 的 List<TimbreFiscalDigital> complemento 字段。要获取 TimbreFiscalDigital 的实例,您必须向 Comprobante 的实例询问该列表并迭代该列表。

你不能通过再次解析 XML 来做到这一点。完整的 XML 已被解析。