JAXB - unmarshal上的XSD验证在缺少属性时不会失败

时间:2014-11-10 17:28:32

标签: xml jaxb xsd xsd-validation

我对unmarshal方法和anattribute的验证有问题。我有一个在我的XSD中设置为“fixed”的属性,当我尝试解组不包含此固定属性的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对象没有任何错误。

我尝试使用Schema XSD添加ValidationEventHandler验证,但不会引发错误。

我的代码中出错了什么?是否将属性设置为“固定”到XSD中以便不会引发错误?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

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

  

默认情况下,属性是可选的。指定属性是   要求,使用&#34;使用&#34;属性:

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

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

非常抱歉给您带来的不便,感谢您的帮助和链接。

答案 1 :(得分:1)

您需要在Unmarshaller上将XML架构设置为javax.xml.validation.Schema的实例,以启用验证。

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
    Schema schema = sf.newSchema(new File("toto.xsd")); 
    unmarshaller.setSchema(schema);

了解更多信息

我在博客上写了更多关于此的内容: