I use Xerces2 Java Parser to validate XML files based on XML Schema 1.1. I have imported all the jars that come with the binary package of Apache Xerces2 Java 2.11.0 (XML Schema 1.1) (Beta) in the maven repository. After some playing around with the configuration, it works fine.
My goal is to validate an XML file that contains no namespace against an XML Schema 1.1.
Schema:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xerces="http://xerces.apache.org">
<xs:element name="root" type="CT_ROOT" />
<xs:complexType name="CT_ROOT">
<xs:sequence>
<xs:element name="myid" type="xs:string" minOccurs="1" />
<xs:element name="mytest" type="ST_Integer" minOccurs="1" />
</xs:sequence>
<xs:assert test="myid gt 100" xerces:message="myid has to be greater than 100" />
</xs:complexType>
<xs:simpleType name="ST_Integer">
<xs:restriction base="xs:integer" xmlns:xerces="http://xerces.apache.org">
<xs:minInclusive value="10" />
<xs:assertion test="$value mod 2 eq 0" xerces:message="Value of element 'test' must be divisible by 2"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
XML File:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<myid>123</myid>
<mytest>60</mytest>
</root>
Java Code:
@Test
public void validateWithXerces() {
System.setProperty("jaxp.debug", "true");
StreamSource schemaDocument = new StreamSource(schemaDocumentString);
Source instanceDocument = new StreamSource(new File(instanceDocumentString));
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1");
Schema schema;
try {
schema = schemaFactory.newSchema(schemaDocument);
Validator validator = schema.newValidator();
validator.validate(instanceDocument);
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is that when the JUnit test runs, the QName class asserts the namespace and it fails. The goal of the specific test is not the validity of the namespace, since it is consciously absent, but the XML validation. Thus we could just ignore the namespace assertion.
The exception thrown is (some lines have been omitted):
java.lang.AssertionError
at org.eclipse.wst.xml.xpath2.processor.internal.types.QName.namespace(QName.java:235)
at org.eclipse.wst.xml.xpath2.processor.DefaultEvaluator.evaluate(DefaultEvaluator.java:239)
at org.apache.xerces.impl.xs.AbstractPsychoPathImpl.evaluatePsychoPathExpr(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.jaxp.validation.ValidatorImpl.validate(Unknown Source)
at javax.xml.validation.Validator.validate(Validator.java:124)
The solution is just to disable the assertions. You can either disable the assertion of a certain class or of every class.
The first solution seems more appropriate. In this case, add the following code in your test class. Just make sure, the piece of code is before the call of the validator.
If you want to disable the assertions for every class, you can do it with Maven: