我正在尝试针对W3C XML Schema验证XML.
以下代码执行作业并报告发生错误的时间.但是我无法得到错误的行号.它总是返回-1.
有没有简单的方法来获得行号?
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.xml.sax.SAXParseException;
public class XMLValidation {
public static void main(String[] args) {
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("myxml.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(new File("myschema.xsd"));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
} catch (SAXParseException e) {
System.out.println(e.getLineNumber());
e.printStackTrace();
} catch (Exception …Run Code Online (Sandbox Code Playgroud) 我正在使用此代码来针对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;
}
Run Code Online (Sandbox Code Playgroud)
但是当XML无效时,消息总是如下所示:
cvc-minLength-valid: Value '-' with length = '1' is not facet-valid with respect to minLength '2' for type '#AnonType_xLgrTEndereco'.
Run Code Online (Sandbox Code Playgroud)
有没有办法以我的语言返回用户友好的消息,而无需以编程方式翻译消息?
更新 这是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>
Run Code Online (Sandbox Code Playgroud)
你可以看到它甚至有一个描述来返回字段的"名称"(Logradouro),但模式验证器似乎不承认它.