Validating XML with multiple XSDs in Java

好久不见. 提交于 2019-12-20 03:12:15

问题


I want to parse an XML file with Java and validate it in the same step against an XSD schema. An XML file may contain content of several schemas, like this:

<outer xmlns="my.outer.namespace" xmlns:x="my.third.namespace">
    <foo>hello</foo>
    <inner xmlns="my.inner.namespace">
         <bar x:id="bar">world</bar>
    </inner>
</outer>

Given a namespace the corresponding xsd file can be provided, but the used namespaces are unknown before parsing. If a schema defines default values for attributes, I also want to know that somehow.

I was able to validate a file if the schemas are known, I was able to parse a file without validation and I implemented a LSResourceResolver. However, I can't get all of it working together. How do I have to set up my (SAX) parser?


回答1:


Who ever designed the Java XML API must have been using drugs...

public void parseAndValidate(File xmlFile, ContentHandler handler) {
    SchemaFactory schemaFactory =
            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new MySchemaResolver());
    Schema schema = schemaFactory.newSchema();

    Validator v = schema.newValidator();
    v.setResourceResolver(schemaFactory.getResourceResolver());

    InputSource is = new InputSource(new FileInputStream(xmlFile));
    v.validate(new SAXSource(is), new SAXResult(handler));
}


来源:https://stackoverflow.com/questions/2829105/validating-xml-with-multiple-xsds-in-java

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