xml - JAXB - 解码时的 XSD 验证不会因缺少属性而失败

标签 xml jaxb xsd xsd-validation

我在解码方法和属性验证方面遇到问题。我的 XSD 中有一个设置为“固定”的属性,当我尝试解码不包含此固定属性的 XML 时,没有出现错误。对我来说,XML 无效,因为该属性不存在并且应该引发异常。

这是我的 XSD:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="toto">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="bigelement">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="oneelement" type="xs:boolean"/>
              <xs:element name="anotherelement" type="xs:string"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:attribute name="name" type="xs:string" fixed="myname"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

这是我尝试解码的 XML:

<?xml version="1.0"?>
<toto>
    <bigelement>
        <oneelement>true</oneelement>
        <anotherelement>hello</anotherelement>
    </bigelement>
</toto>

这是我解码的方法:

    try
    {
      JAXBContext context =JAXBContext.newInstance("com.test");
      Unmarshaller unmarshaller = context.createUnmarshaller();
      Object o = unmarshaller.unmarshal(new StringReader(message));
      Toto command = (Toto)o;
      return command;
    }
    catch (JAXBException e)
    {
      return null;
    }
    catch (ClassCastException e)
    {
      return null;
    }

如您所见,在我的 XML 中我没有设置属性“name”,所以我希望我的 unmarshaller.unmarshal 引发 XML 无效的异常但它构建了Java 对象正确无误。

我尝试添加一个 ValidationEventHandler 并使用 Schema XSD 进行验证,但没有出现错误。

我的代码哪里做错了?是否在 XSD 中将属性设置为“固定”而不会引发错误?

感谢您的帮助。

最佳答案

事实上,我更仔细地阅读了有关属性的 w3schools,我发现:

Attributes are optional by default. To specify that the attribute is required, use the "use" attribute:

<xs:attribute name="lang" type="xs:string" use="required"/>

我一直认为属性是必需的。

对于给您带来的不便,我们深表歉意,感谢您的帮助和链接。

关于xml - JAXB - 解码时的 XSD 验证不会因缺少属性而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26849449/

相关文章:

java - 使用 java 的 XSLT 1.0 中的正则表达式

java - JAXB 元素的属性

java - 将 @Generated 注释添加到 JAXB 生成的类

java - JAXB:解码异构数组

java - 使用 javax.xml.validation.Validator 针对 XSD 进行 XML 验证

c# - 在 C# 中计算 XmlNode 的总数

Java XML dom : prevent collapsing empty element

java - 递归地从 XML 中删除空节点

XSD 模式抽象类型问题

java - xsd - 具有不同类型的相同名称的多个元素