2

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 Answer 1

6

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.