【问题标题】:Ignore few children for comparison when comparing xml documents with XMLUnit将 xml 文档与 XMLUnit 进行比较时忽略少数子项进行比较
【发布时间】:2010-09-16 12:24:57
【问题描述】:

在比较 XML 文档和 XMLUnit 时,是否可以忽略元素中的一些子元素?我想在比较元素时忽略元素中的任何空文本节点。

最好的问候, 凯沙夫

【问题讨论】:

  • 1) 覆盖 DifferenceListener 中的 differenceFound 但随后它会忽略元素中的其他差异。 2) 设置 XMLUnit.setIgnoreWhitespace(true)。这似乎不适用于 compareXML(Document control, Document test)

标签: xml comparison xmlunit


【解决方案1】:

你可以使用这个监听器:

import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceConstants;
import org.custommonkey.xmlunit.DifferenceListener;
import org.w3c.dom.Node;

import java.util.HashSet;
import java.util.Set;

public class IgnoreChildrenOfNamedElementsDifferenceListener implements DifferenceListener {
    public IgnoreChildrenOfNamedElementsDifferenceListener() {}

    public int differenceFound(Difference difference) {
        if (difference.getId() == DifferenceConstants.HAS_CHILD_NODES_ID ||
                difference.getId() == DifferenceConstants.CHILD_NODELIST_LENGTH_ID ||
                difference.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID) {
                return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
            }
        }    
        return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
    }

    @Override
    public void skippedComparison(Node control, Node test) {}
}

那么你可以通过以下方式使用它:

Diff diff = new Diff(expectedDoc, obtainedDoc);
diff.overrideDifferenceListener(new IgnoreChildrenOfNamedElementsDifferenceListener("TestDateTime"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多