如何使用SAX XML Schema Validator的验证消息进行内部化? [英] How to get internalization with validation messages of SAX XML Schema Validator?

查看:433
本文介绍了如何使用SAX XML Schema Validator的验证消息进行内部化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码针对XSD验证XML:

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

但是当XML无效时,消息总是如下所示:

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?

更新
这是XSD中发生消息的字段的一段代码:

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>

你可以看到它甚至有一个描述来返回该字段的名称(Logradouro)但是模式验证器似乎没有认识到它。

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.

推荐答案

这对于隐藏的消息没有帮助,这是不可避免的该API,但API至少提供了一种指定错误发生位置的方法。你可以这样做

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());

将您的消息更改为更像

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

这会告诉您查看第9行第13列以查找无效。

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.

这篇关于如何使用SAX XML Schema Validator的验证消息进行内部化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆