使用Java中的多个XSD验证XML

Cep*_*pod 2 java xml validation xsd sax

我想用Java解析XML文件,并在与XSD架构相同的步骤中验证它.XML文件可能包含多个模式的内容,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

给定命名空间可以提供相应的xsd文件,但在解析之前使用的命名空间是未知的.如果模式定义属性的默认值,我也想以某种方式知道.

如果模式已知,我能够验证文件,我能够解析文件而无需验证,我实现了LSResourceResolver.但是,我无法让所有这些工作在一起.我如何设置我的(SAX)解析器?

Cep*_*pod 6

曾经设计过Java XML API的人一直在使用毒品......

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));
}
Run Code Online (Sandbox Code Playgroud)