[英]How to validate xml against xsd and get *ALL* errors?
我有一个像下面这样的标准代码来验证xml对xsd,但它在第一次错误时抛出异常并停止。 如何验证xml,但继续第一个和下一个错误并最终得到它们? 它甚至可能吗?
public static void validate(File xml, InputStream xsd) {
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(xsd));
Validator validator = schema.newValidator();
StreamSource xmlFile = new StreamSource(xml);
validator.validate(xmlFile);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
在Validator validator = schema.newValidator();
和StreamSource xmlFile = new StreamSource(xml);
添加此片段:
final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
validator.setErrorHandler(new ErrorHandler()
{
@Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
这样,在validate()
您将获得完整的异常列表,但如果发生一个致命错误,解析将停止...
编辑:JavaDoc说: 应用程序必须假定在解析器调用此方法后文档不可用,并且应该继续(如果有的话)只是为了收集其他错误消息:事实上, SAX解析器可以自由停止一旦调用此方法, 报告任何其他事件 。 所以fatalError()
可能会也可能不会导致解析停止。
谢谢你的代码。 我缺少的部分是错误打印到控制台的地方? 现在什么都没发生?!
这就是我得到的:
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
//import java.io.File; // if you use File
import java.io.IOException;
public class ADT_XML_Validator {
public static void main(String xml_pfad) throws IOException {
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource("ADT_GEKID_v2.0.0.xsd"));
Validator validator = schema.newValidator();
final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
validator.setErrorHandler(new ErrorHandler()
{
@Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
StreamSource xmlFile = new StreamSource(xml_pfad);
validator.validate(xmlFile);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.