I've been looking for an example on how to validate an XML file against an XSD schema using JDOM 2.0 before parsing it.

I've been searching for about an hour but wasn't able to find a solution which would work and allow me to provide the path to the XSD file (located on the local file-system) from inside the application code, rather than as an attribute in the XML file.

I am surprised that there is not an easily reachable sample snippet on the Internet already. I would be grateful if you could provide one here.

有帮助吗?

解决方案

Try looking at the XSDSchemaFactory:

http://www.jdom.org/docs/apidocs/org/jdom2/input/sax/XMLReaderXSDFactory.html

For a more general discussion of this look at the package documentation:

http://www.jdom.org/docs/apidocs/org/jdom2/input/sax/package-summary.html

and for some information on the motivation/feature, see the wiki page:

https://github.com/hunterhacker/jdom/wiki/JDOM2-Feature-SAX-Parsing-Updates

If you have more questions, comment here, or drop a note to the jdom-interest mailing list. If you feel the documentation can be improved, please comment on that too.

其他提示

It's very easy to do with JDOM 2. You can do it with 2 lines of code :

SAXBuilder builder = new SAXBuilder(XMLReaders.XSDVALIDATING);
Document document = builder.build(new File("yourXmlFile.xml"));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top