编程语言
首页 > 编程语言> > java – marshal / unmarshal基于2个不同模式的2个不同的类

java – marshal / unmarshal基于2个不同模式的2个不同的类

作者:互联网

我试图在spring beans配置文件中配置jaxb2Marshaller,但我对Spring和JAXB很新,所以我可能会采用错误的方式.

我想要实现的是同一个bean,它将编组/解组基于2个不同模式的2个不同的类.也许那是不可能的,因为当我配置并运行我的测试时,他们在配置(AccountResponse)中的第二个类失败了.

这是XML配置:

<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="marshallerProperties">
        <map>
            <entry key="com.sun.xml.bind.namespacePrefixMapper">
                <bean id="NamespacePrefixMapperImpl" class="org.lp.soa.controller.xml.LpsNamespacePrefixMapper" />
            </entry>
        </map>
    </property>
    <property name="classesToBeBound">
        <list>                              
            <value>org.lp.soa.controller.data.request.AccountRequest</value>
            <value>org.lp.soa.controller.data.response.AccountResponse</value>
        </list>
    </property>     
    <property name="schemas">
        <list>
        <value>classpath:schema/AccountRequest.xsd</value>
        <value>classpath:schema/AccountResponse.xsd</value>
        </list>
    </property>
</bean>

如果我从配置中注释掉AccountRequest.xsd值,然后再次运行我的测试,那么第二个类(AccountResponse)的编组/解组它们都会通过,如果我取消注释它,我会得到错误:org.xml.sax.SAXParseException :cvc-elt.1:找不到元素’accountResponse’的声明.

我是以错误的方式去做的吗?难道不应该用两个模式处理两个类吗?

谢谢,
约阿夫.

解决方法:


if i comment out the AccountRequest.xsd value from the config and then
run my tests again the marshal/unmarshal for the second class
(AccountResponse) they all pass, if I then uncomment it I get the
error: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the
declaration of element ‘accountResponse’.

听起来像SchemaFactory.newSchema()创建的Schema对象只处理列表中的第一个xsd.

如果你有多个模式文件在同一个命名空间(targetNamespace?),那么可能是这个bug造成了麻烦:

https://issues.apache.org/jira/browse/XERCESJ-1130

我解决这个错误的方法是创建一个包含其他xsd文件的父xsd文件,然后使用LSResourceResolver实现在xml配置中设置“schemaResourceResolver”属性(例如参见http://blog.frankel.ch/xml-validation-with-importedincluded-schemas).

在您的xml配置中添加以下内容:
    

parent.xsd文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.yourdomain.com/FIXED/EXAMPLE"
           targetNamespace="http://www.yourdomain.com/FIXED/EXAMPLE"
           elementFormDefault="qualified"
           version="1.000"
           id="some_id">
    <xs:include schemaLocation="AccountRequest.xsd"/>
    <xs:include schemaLocation="AccountResponse.xsd"/>
</xs:schema>

在xml配置中,将schemas属性更改为:

<property name="schemas">
        <list>
        <value>classpath:schema/parent.xsd</value>
        </list>
</property>

标签:jaxb2,java,spring,xml
来源: https://codeday.me/bug/20190826/1728796.html