Can XMLCatalog be used for schema imports?

梦想的初衷 提交于 2019-12-04 04:17:17

问题


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.


回答1:


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())


来源:https://stackoverflow.com/questions/981382/can-xmlcatalog-be-used-for-schema-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!