开发者

SAXException when parsing XML file with XSD schema

开发者 https://www.devze.com 2023-01-18 19:51 出处:网络
I have the following XSD file: <xs:schema xmlns:xs=\'http://www.w3.org/2001/XMLSchema\' targetNamespace=\'http://www.wvf.com/schemas\'

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'>

 <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">
</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.newSchem开发者_C百科a(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?


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"; 
0

精彩评论

暂无评论...
验证码 换一张
取 消