【问题标题】:JAXB xml validationJAXB xml 验证
【发布时间】:2014-02-27 06:00:26
【问题描述】:

在 xsd 架构中,我使用未在架构中定义的类的继承(出于错误原因,它在其他模块/包中)定义为:

 <xsd:complexType name="RemoteHost">
   <xsd:annotation>
     <xsd:appinfo>  
       <jaxb:class ref="com.dummy.entities.RemoteHost"></jaxb:class>
     </xsd:appinfo>
   </xsd:annotation>
 </xsd:complexType>

例如,子类在同一个 xsd 文档中定义为:

<xsd:complexType name="hostFirstSubType">
    <xsd:complexContent>
        <xsd:extension base="RemoteHost">
        </xsd:extension>        
    </xsd:complexContent>        
</xsd:complexType>

<xsd:complexType name="otherHostType">
    <xsd:complexContent>
        <xsd:extension base="RemoteHost">
            <xsd:attribute name="id" type="xsd:int" />
        </xsd:extension>            
    </xsd:complexContent>        
</xsd:complexType> 

在 xsd 中的子类定义为:

@SuppressWarnings("restriction")
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "GenericRemoteHost",propOrder = {
        "address",
        "username",
        "password",
        "sshPort"
    })
public class RemoteHost {

    @XmlElement(required = true, namespace = "http://com/dummy/entities/RemoteHost")
    protected String  address;
    @XmlElement
    protected String  username;
    @XmlElement
    protected String  password;
    @XmlElement
    protected Integer sshPort;
    ...

要加载的 xml 示例部分:

        <hostFirstSubType>
            <rh:address>127.0.0.1</rh:address>
            <rh:username>user</rh:username>
            <rh:password>pass</rh:password>                             
            <rh:sshPort>22</rh:sshPort>             
        </hostFirstSubType>

        <otherHostType id="1">
            <rh:address>127.0.0.1</rh:address>
            <rh:username>user</rh:username>
            <rh:password>pass</rh:password>                             
            <rh:sshPort>22</rh:sshPort>             
        </otherHostType>    

我创建了一个验证收集器,用于在针对该架构解组 xml 文件期间显示所有验证错误,结果令人困惑: 验证收集器将继承我的 RemoteHost 的每个类显示为验证错误:

元素“hostFirstSubType”不能有字符或元素 信息项 [children],因为该类型的内容类型为空。

元素 'otherHostType' 必须没有字符或元素信息 item [children],因为该类型的内容类型为空

但是,当我跳过验证部分时,xml 文件被正确加载到 java 对象中,所有数据都被加载并使用 getter 和 setter 访问。

按照其他一些帖子的建议,我尝试将 @XmlAccessorType(XmlAccessType.NONE) 更改为其他可用值,但没有成功。

任何人都知道还有什么要寻找的......

【问题讨论】:

    标签: java xml validation jaxb xsd


    【解决方案1】:

    您看到的行为与您的行为相符:

    1. 您的 XML 包含未在您的 XML 架构中定义的元素,因此您会遇到验证错误。
    2. 您的 XML 包含映射到您的对象模型的元素,并且工作正常。

    你可以做的事情:

    1. 将文档中 XML 元素的定义包含到 XML 架构中。
    2. 利用any 概念使您的XML 元素的定义更加灵活。

    【讨论】:

    • 说实话,我不知道该怎么办。关于 xml,它不包含任何未在超类中定义的数据。我尝试将超类的一些 xsd 定义直接添加到 xsd,例如在 xsd 中的 RemoteHost 定义中定义序列元素,但问题仍然存在。你能帮我举个例子或链接吗...
    猜你喜欢
    • 2014-11-28
    • 2017-05-19
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 2014-09-05
    • 2012-07-01
    • 1970-01-01
    相关资源
    最近更新 更多