App validates XML against XSD: allow XSD reference in XML

My application validates a XML against a XSD (which is in the jar):

private Document createAndValidate(Schema schema) throws IOException, SAXException, ParserConfigurationException {
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  documentBuilderFactory.setValidating(false); // DTD validation
  documentBuilderFactory.setNamespaceAware(false);
  documentBuilderFactory.setSchema(schema);

  DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  documentBuilder.setErrorHandler(new SaxErrorHandler());

  return documentBuilder.parse(file.toFile());
}

That works fine so far.

But since it’s easier to create the XML with the XSD (which could be anywhere on the local computer) referenced, the XML starts like this:

<?xml version="1.0" encoding="UTF-8"?>
<Definition
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="C:\definition_schema.xsd">

Now, when my application parses that XML file, it fails to validate because of this XSD reference:
cvc-complex-type.3.2.2: Attribute 'xsi:noNamespaceSchemaLocation' is not allowed to appear in 'Definition'

I tried to add <xs:attribute name="xsi:noNamespaceSchemaLocation" type="xs:string" /> to the Definition element, but that attribute name isn’t valid.

I could open the XML file and remove the attribute before I (re)open and validate it. But there must be a better solution.

How do I handle this?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s