5

I am trying out some XML Schema examples and have to validate them with a sample XML File. The schema is a local file (someFile.xsd). I am using eclipse and want to include a reference in the XML file to point to this local xsd file so that eclipse can suggest the elements to me.

Am finding it hard to come up with the syntax to include a local file. Any suggestions ?

Arun R
  • 8,372
  • 6
  • 37
  • 46

3 Answers3

3

Are you using the xsi:schemaLocation attribute?

Ex:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://foo/target/Namespace"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:someNamespace="someFile"     
       xsi:schemaLocation="
       someFile someFile.xsd" >
...
</root>

I believe someFile.xsd has to be in your classpath

Scott Bale
  • 10,649
  • 5
  • 33
  • 36
0

Does something like this work?

<?xml version="1.0"?>
<note
xmlns="http://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com note.xsd">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

Copied from http://www.w3schools.com/Schema/schema_howto.asp

Andre
  • 1,601
  • 3
  • 15
  • 15
0

You can set your own Implementation of ResourceResolver and LSInput to the SchemaFactory so that the call of of LSInput.getCharacterStream() will provide a schema from a local path.

It tried to provide a comprehensive example here.

The approach basically consists of a proper implementation of what is called from

getSchemaAsStream(input.getSystemId(), input.getBaseURI(), localPath)));

at the end of the following code. At this point you have to hook in with your own lookup mechanism to find schema files on your local path.

public void validate(InputStream xmlStream, InputStream schemaStream, String baseUri, String localPath)
                throws SAXException, IOException {
    Source xmlFile = new StreamSource(xmlStream);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver((type, namespaceURI, publicId, systemId, baseURI) -> {
        LSInput input = new DOMInputImpl();
        input.setPublicId(publicId);
        input.setSystemId(systemId);
        input.setBaseURI(baseUri);
        input.setCharacterStream(new InputStreamReader(
                        getSchemaAsStream(input.getSystemId(), input.getBaseURI(), localPath)));
        return input;
    });
jschnasse
  • 8,526
  • 6
  • 32
  • 72