gpt4 book ai didi

java - JAXB xml 验证

转载 作者:太空宇宙 更新时间:2023-11-04 15:09:27 25 4
gpt4 key购买 nike

在 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 的每个类的验证错误:

Element 'hostFirstSubType' must have no character or element information item [children], because the type's content type is empty.

Element 'otherHostType' must have no character or element information item [children], because the type's content type is empty

但是,当我跳过验证部分时,xml 文件已正确加载到 java 对象中,所有数据均已加载并可通过 getter 和 setter 进行访问。

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

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

最佳答案

您所看到的行为与您所拥有的行为相符:

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

你可以做的事情:

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

关于java - JAXB xml 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21532631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com