【问题标题】:Ignore certain elements while compating xml XMLUnit在兼容 xml XMLUnit 时忽略某些元素
【发布时间】:2017-02-03 15:30:41
【问题描述】:

我想在一项 Junit 测试中比较两个 XML。 我正在使用 XMLUnit 来比较 xml。你能告诉我是否有任何简单的方法可以忽略 xmls 中 correlation-id 的比较。

XML1:

<?xml version="1.0" encoding="UTF-8"?>
<response>
<bih-metadata>
<result>Error</result>
<correlation-id>ID:925977d0-83cd-11e6-b94d-c135e6c73218</correlation-id>
<error-message>SAXParseException: The entity name must immediately follow the '&amp;' in the entity reference.</error-message>
</bih-metadata>
</response>

XML2:

<?xml version="1.0" encoding="UTF-8"?>
<response>
<bih-metadata>
<result>Error</result>
<correlation-id>ID:134345d0-83cd-11e6-b94d-c135e6c73218</correlation-id>
<error-message>SAXParseException: The entity name must immediately follow the '&amp;' in the entity reference.</error-message>
</bih-metadata>
</response>

【问题讨论】:

  • 能否请您添加您的代码示例?

标签: java xml junit xmlunit


【解决方案1】:

这是在 XMLUnit 2.x 中添加的 NodeFilter

import org.w3c.dom.Element;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.util.Nodes;
import org.xmlunit.diff.*;

public class Test {

    public static void main(String[] args) {
        Diff d = DiffBuilder.compare("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                                     "<response>\n" +
                                     "<bih-metadata>\n" +
                                     "<result>Error</result>\n" +
                                     "<correlation-id>ID:925977d0-83cd-11e6-b94d-c135e6c73218</correlation-id>\n" +
                                     "<error-message>SAXParseException: The entity name must immediately follow the '&amp;' in the entity reference.</error-message>\n" +
                                     "</bih-metadata>\n" +
                                     "</response>")
            .withTest("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                      "<response>\n" +
                      "<bih-metadata>\n" +
                      "<result>Error</result>\n" +
                      "<correlation-id>ID:134345d0-83cd-11e6-b94d-c135e6c73218</correlation-id>\n" +
                      "<error-message>SAXParseException: The entity name must immediately follow the '&amp;' in the entity reference.</error-message>\n" +
                      "</bih-metadata>\n" +
                      "</response>")
            .withNodeFilter(n -> !(n instanceof Element && "correlation-id".equals(Nodes.getQName(n).getLocalPart())))
            .build();
        System.err.println("Different? " + d.hasDifferences());
    }
}

【讨论】: