Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get internalization with validation messages of SAX XML Schema Validator?

I'm using this code to validate a XML against a XSD:

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema(xmlSchema);
Validator validator = schema.newValidator();
Source source = new StreamSource(myXmlFile);

try {
    validator.validate(source);
    return null;
}catch (SAXException ex) {
    String validationMessage = ex.getMessage();
    return validationMessage;
}

But when the XML is not valid, the message is always something like this:

cvc-minLength-valid: Value '-' with length = '1' is not facet-valid with respect to minLength '2' for type '#AnonType_xLgrTEndereco'.

Is there a way to return a user friendly message in my language, without having to translate the message programatically?

UPDATE This is piece of code in the XSD for the field in which the message occured:

<xs:element name="xLgr">
    <xs:annotation>
        <xs:documentation>Logradouro</xs:documentation>
    </xs:annotation>
    <xs:simpleType>
        <xs:restriction base="TString">
            <xs:maxLength value="60"/>
            <xs:minLength value="2"/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

As you can see it even has a description to return the "name" of the field (Logradouro) but the schema validator seems not to recognize it.

like image 255
Mateus Viccari Avatar asked Jan 02 '16 12:01

Mateus Viccari


1 Answers

It doesn't help with the message being cryptic, which is unavoidable with that API, but the API does at least provide a way to specify where the error occurred. You could do something like

return String.format("%d:%d %s",ex.getLineNumber(),ex.getColumnNumber(),ex.getMessage());

to change your message to something more like

9:13 cvc-minLength-valid: Value '-' with length = '1' is not facet-valid with respect to minLength '2' for type '#AnonType_xLgrTEndereco'.

which would tell you to look at line 9, column 13 to find the invalidity.

At very least, this will allow your messages to specify exactly where the error is.

like image 126
Matthew Avatar answered Nov 09 '22 22:11

Matthew