开发者

how to do validation with not well form XML while doing unmarshalling?

I have an unmarshaller along with an MySchema.xsd file.

    StreamSource sources = new StreamSource(getClass().getClassLoader().getResourceAsStream("/xmlValidation.xsd"));
    SchemaFactory sf = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
    unmarshaller.setSchema(sf.newSchema(sources));

And make a call to unmarshaller.setEventHandler() function, to specify a custom validation event handler, which basically format a error tips string , by:

    final String errorString = new String();
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override
        public boolean handleEvent(ValidationEvent validationevent) {
            if(validationevent.getSeverity()!= ValidationEvent.WARNING){
                errorString.format( "Line:Col[" + validationevent.getLocator().getLineNumber()
                                    + ":" + validationevent.getLocator().getColumnNumber()
                                    + "]:" + validationevent.getMessage());
                return false;
            }
            return true;
        }
    });

The above codes seem work ok(I can get java object when the input string is validated. and also the 开发者_StackOverflowerror tips string is formated as excepted)

The problem is that, when the input xml is not well form, it also throw a SaxParseException.

Thanks in advance. Andrew


Well formed relates to the XML syntax itself, as opposed to being valid WRT an XML schema:

  • http://en.wikipedia.org/wiki/Well-formed_element

If you have XML that is not well formed then you will get a ValidationEvent.FATAL_ERROR and unmarshalling will not be able to continue, as the underlying parser used by JAXB cannot continue.

For more information:

  • http://bdoughan.blogspot.com/2010/12/jaxb-and-marshalunmarshal-schema.html


K, I mess up something and get this problem. Now I figure it out. If I am wrong, please point me out. below it's what I find in javadoc and test on my project:

javax.xml.bind.ValidationEventHandler can handler the constrain error with the given schema constrains, when unmarshaller is unmarshaling.

unmarshaller.unmarshal(xmlInputStream);

The ValidationEventHandler will be called during the unmarshaling process if error occurs. The SAXEception will be thrown, if the xmlInputStream is not well form. And I cant find a way to catch the SAXException, throw by the sax parser, so I guess using validation during unmarshaling can't due with un-well form xml string.


I use javax.xml.validation.Validator to validate that the xml string is well form and under constrain.

jaxbValidator.validate(xmlSource);

The above code will throw SAXException. If no exception is thrown, then unmarshall the xml string into object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜