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

时间:2012-05-30 21:23:09

标签: java xml spring jaxb2

我试图在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'的声明。

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

谢谢, 约阿夫。

2 个答案:

答案 0 :(得分:5)

  

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

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

如果您有多个模式文件位于同一名称空间(targetNamespace?),那么可能是这个导致问题的错误:

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>

答案 1 :(得分:1)

尝试使用MOXy。您可以拥有由注释定义的模式映射,以及在xml文件中配置的其他映射。

据我所知,XStream不提供xml验证,因此您可以在解组之前尝试进行模式验证。 使用JAXB,您可以使用@XmlElement/@XmlAttribute(required=true)注释验证所需的元素/属性。