如何在根据 XML 架构验证 XML 文件时获取错误的行号
我正在尝试针对 W3C XML 架构验证 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 e) {
e.printStackTrace();
}
}
}