tags:

views:

35

answers:

1

I have the following XSD file:

<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'
           targetNamespace='http://www.wvf.com/schemas'
           xmlns='http://www.wvf.com/schemas'
           xmlns:acmewvf='http://www.wvf.com/schemas'&gt;

 <xs:element name='loft'>
 </xs:element>
</xs:schema>

and the following XML file:

<?xml version="1.0"?>

<acmewvf:loft xmlns:acmewvf="http://www.wvf.com/schemas"
               xmlns="http://www.wvf.com/schemas"&gt;
</acmewvf:loft>

When I execute the following Java code:

public void parse(InputStream constraints) {
    final SchemaFactory schemaFactory = new XMLSchemaFactory();
    final URL resource = 
        ClassLoader.getSystemClassLoader().getResource(SCHEMA_PATH);
    final DocumentBuilderFactory factory = 
        DocumentBuilderFactory.newInstance();
    Document doc = null;
    factory.setSchema(schemaFactory.newSchema(resource));
    final DocumentBuilder builder = factory.newDocumentBuilder();
    doc = builder.parse(constraints);

I get the following SAXException (on the last line of the code):

cvc-elt.1: Cannot find the declaration of element 'acmewvf:loft'.

(Note that SCHEMA_PATH points to the XSD file whose contents are given above and constraints is an input stream to the XML file whose contents are also given above.)

What's going wrong here?

+1  A: 

See Using the Validating Parser. Probably, you should try to add the following to generate a namespace-aware, validating parser:

  factory.setNamespaceAware(true);
  factory.setValidating(true);
try {
  factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
} 
catch (IllegalArgumentException x) {
  // Happens if the parser does not support JAXP 1.2
  ...
} 

Don't forget to define:

static final String JAXP_SCHEMA_LANGUAGE =
    "http://java.sun.com/xml/jaxp/properties/schemaLanguage";

static final String W3C_XML_SCHEMA =
    "http://www.w3.org/2001/XMLSchema"; 
Shcheklein