如何禁用XMLUNIT DTD验证



我正在尝试使用xmlunit 2.2.0比较两个XHTML文档。但是,这花费了太长时间。我想图书馆正在从Internet下载DTD文件。

如何禁用DTD验证?我正在使用以下测试代码:

public class Main {
    public static void main(String args[]) {
        Diff d = DiffBuilder.compare(
                Input.fromString(
                     "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" n"
                    +"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">n"
                    +"<html xmlns="http://www.w3.org/1999/xhtml">n"
                    +"     <head></head>n"
                    +"     <body>some content 1</body>n"
                    +"</html>")).withTest(
                Input.fromString(                   
                     "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" n"
                    +"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">n"
                    +"<html xmlns="http://www.w3.org/1999/xhtml">n"
                    +"     <head></head>n"
                    +"     <body>some content 2</body>n"
                    +"</html>")).ignoreWhitespace().build();
        if(d.hasDifferences()) 
            for (Difference dd: d.getDifferences()) {
                System.out.println(dd.toString());
            }
    }
}

阅读DiffBuilder.withDocumentBuilderFactory()的XMLUNIT JAVADOC,我想我可以这样做,将文档构建器工厂设置为这样...

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setFeature("http://xml.org/sax/features/validation", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
Diff d = DiffBuilder.compare(Input.fromString(...)).withTest(
     Input.fromString(...)).withDocumentBuilderFactory(dbf)
          .ignoreWhitespace().build();

它不起作用。当我从XHTML摘要中删除Doctype定义时,我的代码很快就运行。

withDocumentBuilderFactory正是您想要使用的,但不幸的是ignoreWhitespace击败了它。

封面下的DiffBuilder在不使用已配置的DocumentBuilderFactory的情况下创建DOM DocumentWhitespaceStrippedSource。这是一个错误。您想为此创建一个问题吗?

使用XMLUNIT 2.2.0的解决方法是自己创建Document S,例如

Document control = Convert.toDocument(Input.fromString(...).build(), dbf);
Document test = ...
Diff d = DiffBuilder.compare(Input.fromDocument(control))
             .withTest(Input.fromDocument(test))
             .ignoreWhitespace().build();

编辑:该错误已在XMLUNIT 2.2.1中固定,现在问题的代码应该在没有任何更改的情况下工作。

最新更新