且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java XML 解析/验证错误处理

更新时间:2022-12-07 22:03:05

要处理错误,您必须实现接口 ErrorHandler 或扩展 DefaultHandler 帮助器类和重新定义 error 方法.这就是调用验证错误的方法.如果你想更精确,我认为你必须分析错误信息.我认为 SaX 不会为您提供易于修复错误的功能.

To deal with errors you have to implement the interface ErrorHandler or to extend the DefaultHandler helper class and redefine the error method. That is the method called for validation errors. If you want to be more precise, I think that you will have to analyze the error message. I don't think SaX will give you something that makes errors easy to fix.

顺便说一句,请注意,为了针对 XSD 进行验证,您不应使用 setValidating 方法.请参阅下面的代码.

BTW, note that for validating against an XSD, you should not use the method setValidating. See the code below.

setValidating 方法的 Java 文档 (1.7) 说:

The Java doc (1.7) of the setValidating method says :

注意验证"这里指的是 XML 建议中定义的验证解析器.换句话说,它本质上只是控制 DTD 验证.(JAXP 1.2 中定义的遗留两个属性除外.)

Note that "the validation" here means a validating parser as defined in the XML recommendation. In other words, it essentially just controls the DTD validation. (except the legacy two properties defined in JAXP 1.2.)

要使用现代模式语言(例如 W3C XML Schema 或 RELAX NG 而不是 DTD,您可以通过将 setValidating(boolean) 方法保留为 false 将解析器配置为非验证解析器,然后使用 setSchema(Schema) 方法将架构关联到解析器.

To use modern schema languages such as W3C XML Schema or RELAX NG instead of DTD, you can configure your parser to be a non-validating parser by leaving the setValidating(boolean) method false, then use the setSchema(Schema) method to associate a schema to a parser.

import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
// ...
public static void main(String args[]) throws Exception {
        if (args.length == 0 || args.length > 2) {
            System.err.println("Usage: java Validator <doc.xml> [<schema.xsd>]");
            System.exit(1);
        }
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.    W3C_XML_SCHEMA_NS_URI);
        String xsdpath = "book.xsd";
        if (args.length == 2) {
            xsdpath = args[1];
        }
        Schema s = sf.newSchema(new File(xsdpath));
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setSchema(s);
        
        XMLReader parser = factory.newSAXParser().getXMLReader();
        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

        PrintStream out = new PrintStream(System.out, true, "UTF-8");
        parser.setContentHandler(new MyHandler(out));
        parser.setErrorHandler(new DefaultHandler());
        parser.parse(args[0]);
    }
}