I have a simple schema validator method:
// Throws runtime exception if anything goes wrong.
public void validate(String schemaURL, String xml) throws Throwable {
SAXParserFactory oSAXParserFactory = SAXParserFactory.newInstance();
SAXParser oSAXParser = null;
oSAXParserFactory.setNamespaceAware(true);
SchemaFactory oSchemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
oSAXParserFactory.setSchema(oSchemaFactory.newSchema(new URL(schemaURL)));
oSAXParser = oSAXParserFactory.newSAXParser();
SaxErrorHandler handler = new SaxErrorHandler();
oSAXParser.parse(new InputSource(new StringReader(xml)),handler);
}
I have a schema hosted at http://myserver.com/schemas/app-config/1.0/app-config-1.0.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="application">
<xs:complexType>
<xs:choice>
<xs:element ref="info"/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name="info">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
</xs:schema>
Observe the follow instance of that schema:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://myserver.com/schemas/app-config/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://myserver.com/schemas/app-config/1.0
http://myserver.com/schemas/app-config/1.0/app-config-1.0.xsd">
<info
name="Dummy Application"
/>
</application>
When I pass my validate method the following:
String xmlInstance = readXMLIntoString();
String schemaURL = "http://myserver.com/schemas/app-config/1.0/app-config-1.0.xsd";
validate(schemaURL, xmlInstance);
I get the following error:
org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element ‘application’.
- Is something wrong with my schema?
- Is something invalid with my instance?
- Is there a problem with me actually hosting the schema at the URL (although the one used in this example is a mockup, I assure you that the XSD file really is hosted at the URL I’m hitting in the code)?
Why can’t the validator find application declaration?
My original answer stated that schemaLocation was incorrect, which is in fact the case, but for a different reason than I suggested originally. As Kohányi Róbert said, your schema is missing a
targetNamespace. Either follow his approach and modify your schema, or replaceschemaLocationwithnoNamespaceSchemaLocation.