XML File with local copy of XML Schema

后端 未结 3 1038
悲哀的现实
悲哀的现实 2021-01-13 02:38

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 03:20

    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;
        });
    

提交回复
热议问题