How can one validate an XML file using an XSD in Java? We don’t know the schema in advance. I would like to be able to get the schemaLocation, download the XSD, cache it and then perform the actual validation.
The problem is, that with javax.xml.parsers.DocumentBuilder/DocumentBuilderFactory classes I can’t seem to be able to get a hold of the schemaLocation in advance. What’s the trick for this? Which classes should I look into?
Perhaps there’s a more suitable API I can use? The whole problem is that we need to validate dynamically, without (necessarily) having the XSDs locally.
How could one get a hold of the URL of schemaLocation defined in the XSD file?
I know you can set features/attributes, but that’s a different thing. I need to get the schemaLocation from the XSD first.
Please advise!
Given that you are using Xerces (or JDK default), have you tried setting this feature to true on the factory: http://apache.org/xml/features/validation/schema. There are other features that you can play with regarding schemas: http://xerces.apache.org/xerces2-j/features.html
UPDATE 2 (for caching):
Implement a
org.w3c.dom.ls.LSResourceResolverand set this on theSchemaFactoryusing thesetResourceResolvermethod. This resolver would either get the schema from cache or fetch it from wherever the location refers to.UPDATE 3:
LSResourceresolver example (which I think will be a good starting point for you):
The implementation of MyLSInput is really boring: