Question

Can you use XMLCatalog to resolve xsds in schema import statements? If so, what is the preferred/best practice? I want to package the xsds in a jar, so using a relative schemaLocation has not worked.

So far I am trying to do something like:

SchemaFactory factory = SchemaFactory
        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
XMLCatalogResolver catalogResolver = new XMLCatalogResolver(
        new String[]{"/path/to/catalog.xml"});
factory.setResourceResolver(catalogResolver);

Schema schema = factory.newSchema(new StreamSource(ClassLoader
        .getSystemResourceAsStream("config.xsd")));

Without much luck.

Was it helpful?

Solution

At a quick look I see two problems:

XMLCatalogResolver catalogResolver = new XMLCatalogResolver(
        new String[]{"catalog.xml"});

If you look at the Javadoc for this method you can read

catalogs - an ordered array list of absolute URIs

which is not what you use.

The second problem is here

Schema schema = factory.newSchema(new StreamSource(ClassLoader
        .getSystemResourceAsStream("config.xsd")));

You do not set the system id for the schema so if you have a relative location for the import then that will be resolved relative to the current directory of your application instead of the directory where you have your schema file. You need to either to call setSystemId on the source or pass the system id when you create it:

new StreamSource(ClassLoader.getSystemResource("config.xsd").toString())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top