我使用此代码根据 XSD 验证 XML:
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 无效时,消息总是如下所示:
cvc-minLength-valid: Value '-' with length = '1' is not facet-valid with respect to minLength '2' for type '#AnonType_xLgrTEndereco'.
有没有办法以我的语言返回用户友好的消息,而无需以编程方式翻译消息?
UPDATE这是 XSD 中出现消息的字段的代码段:
<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),但模式验证器似乎无法识别它。
它对消息的神秘性没有帮助,而对于该 API 来说这是不可避免的,但 API 至少提供了一种方法来指定错误发生的位置。你可以做类似的事情
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 列以查找无效性。
至少,这将允许您的消息准确指定错误所在。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)