开发者

Validating XML with multiple XSDs in Java

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 g开发者_StackOverflow社区et all of it working together. How do I have to set up my (SAX) parser?


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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜