JAXB - XSD validation on unmarshal do not fail on missing attribute



I have a problem with the unmarshal method and the validation of anattribute. I have an attribute that is set as "fixed" in my XSD and when I tried to unmarshal a XML which does not contain this fixed attribute, no error is raised. For me, the XML is not valid because the attribute is not present and should raise an exception.


Here is my XSD :



<?xml version="1.0"?>
<xs:schema xmlns:xs="http://ift.tt/tphNwY">
<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>


Here is my XML I try to unmarshal :



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


And here is my method that unmarshal:



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;
}


As you can see, in my XML I didn't set the attribute "name", so I expect that my unmarshaller.unmarshal raises an exception that the XML is not valid but it builds the Java Object correctly without any error.


I tried to add a ValidationEventHandler with a validation with the Schema XSD but no error is raised.


What am I doing wrong in my code? Is it the fact that the attribute is set as "fixed" into the XSD that no error is raised?


Thanks for the help.


No comments:

Post a Comment