java - 使用生成的代码 (moxy) : "A descriptor with default root element ... was not found in the project" 解码时出错

标签 java xml jaxb unmarshalling moxy

我使用 moxy 为不同的 xsd 文件生成了代码: http://www.forum-datenaustausch.ch/generalinvoiceresponse_400.xsdhttp://www.forum-datenaustausch.ch/xmlstandards_generelle_rechnung_beispiele_antwort_4.3_20100901.zip

我为两个 xsd 生成了 jaxb 类(使用 moxy)。然后我尝试使用以下代码解码 xml 文件(由 eclipse 生成):

public void tempTest() throws JAXBException{
    JAXBContext jC = JAXBContext.newInstance(<package for corresponding type>.ResponseType.class);
    jC.createUnmarshaller().unmarshal(ResponseTest.class.getResourceAsStream("/responses/generalInvoiceResponse_400.xml"));
}

对于 4.3 类型的 xml 文件(第二个链接),这工作正常但是对于 400 类型的 xml(第一个链接)我得到这个错误:

Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element {http://www.forum-datenaustausch.ch/de}response was not found in the project]

这似乎是 namespace 的问题。 namespace 不同,但我看不到生成的代码或生成的 xml 的相关差异 - namespace 是一致的。 那么是什么导致了这个问题(区别在哪里)以及如何解决呢?

小补充:我还尝试解码用 jaxb/moxy-code 编码的 xml:

public void marshall() throws JAXBException, FileNotFoundException {
    JAXBContext jC = JAXBContext.newInstance(ResponseType.class);
    ObjectFactory of = new ObjectFactory();
    jC.createMarshaller().marshal( of.createResponse(of.createResponseType()),new FileOutputStream("simpleresponse.xml"));
}

这将创建一个非常简单的 xml:

<?xml version="1.0" encoding="UTF-8"?>
<response xmlns="http://www.forum-datenaustausch.ch/de"/>

对此进行解码会产生相同的错误

最佳答案

当基于从 XML 模式生成的模型创建 JAXBContext 时,您应该始终使用采用包名称的 newInstance 方法。这将确保处理所有必要的位。

JAXBContext jC = JAXBContext.newInstance("ch.forum_datenaustausch.de");

当您使用 JAXBContext.newInstance(Class...) 方法时,JAXB 实现假设您是从 Jav 类开始的。由于 ObjectFactory 的角色可以由任何用 @XmlRegistry 注释的类扮演,从 XML 模式生成的 ObjectFactory 类将被自动选取。您可以执行以下操作,但我仍然推荐上述方法:

JAXBContext jC = JAXBContext.newInstance(ResponseType.class, ObjectFactory.class);

更新

Thank you! but could you probably explain why it is working with one xsd and not with the other?

它“工作”的模式可能有一个匿名类型的全局元素,这会导致生成一个 @XmlRootElement 注释,这意味着不需要 ObjectFactory。另一个可能有一个具有命名复杂类型的全局元素,这会导致生成 ObjectFactory 类上的 @XmlElementDecl 注释。

关于java - 使用生成的代码 (moxy) : "A descriptor with default root element ... was not found in the project" 解码时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16667476/

相关文章:

java - 如何只用它的键定义一个 JSONObject

java - Comparable接口(interface)——如何比较int类型?

css - 如何在网页中显示手机壳背面(带有透明相机孔)等形状内的图像?

xml - 从命令行合并多个 XML 文件

返回 JAXB 带注释的对象时,具有非标准的 Spring Boot RequestMapping 会产生返回 406 错误的值

inheritance - eclipselink/Moxy : inheritance and attribute name oveloading based on type

java - 如何在Android上使用Intent获取文件夹路径

java - 解析一个大的 xml 文件 Java

java - xsd :datetime and XmlGregorianCalendar causes NullPointerException

java - Maven 依赖版本不匹配问题 - 从 repo 解决依赖的过时版本