0

我正在使用 XMLUnit 2.xx 比较 2 个 XML,它们都具有相同的结构,但根节点名称除外:

<expectedValue>
  <elementA>something</elementA>
  <elementB>something else</elementB>
  <elementC>yet another thing</elementC>
</expectedValue>

<value>
  <elementA>something</elementA>
  <elementB>something else</elementB>
  <elementC>yet another thing</elementC>
</value>

我正在寻找一种方法来告诉 diffBuilderexpectedValue == value或者最终忽略这个特定的比较。

任何想法 ?谢谢

4

2 回答 2

0

我找到了一种忽略 2 个特定标签名称的特定比较的方法。

如果有人需要,我会在这里给出答案

首先制作一个自定义的DifferenceEvaluator:

public class IgnoreTagNameDifferenceEvaluator implements DifferenceEvaluator {

    Map<String,String> map;

    public IgnoreTagNameDifferenceEvaluator(Map<String,String> map){
        this.map = map;
    }

    @Override
    public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
        if (outcome == ComparisonResult.EQUAL) return outcome; // only evaluate differences.

        if(comparison.getType() == ComparisonType.ELEMENT_TAG_NAME){
            String value = map.get(comparison.getControlDetails().getValue());
            if(value != null && value.equals(comparison.getTestDetails().getValue())){
                return ComparisonResult.SIMILAR;
            }
        }
        return outcome;
    }
}

然后像这样将它链接到 diffBuilder :

diffBuilder = diffBuilder.withDifferenceEvaluator(DifferenceEvaluators.chain(
                DifferenceEvaluators.Default, new IgnoreTagNameDifferenceEvaluator(tagMap)));
于 2018-03-07T08:08:08.817 回答
0

这在很大程度上改变了 XML 中平等的想法 :-)

您需要做两件事,首先您需要提供ElementSelector自己的一个告诉 XMLUnit 甚至比较expectedValuevalue节点。在第二部分中,您需要一个DifferenceEvaluator说明节点名称的差异很好。

就像是

public static void main(String[] args) {
    String x1 = "<expectedValue>"
        + "  <elementA>something</elementA>"
        + "  <elementB>something else</elementB>"
        + "  <elementC>yet another thing</elementC>"
        + "</expectedValue>";
    String x2 = "<value>"
        + "  <elementA>something</elementA>"
        + "  <elementB>something else</elementB>"
        + "  <elementC>yet another thing</elementC>"
        + "</value>";
    NodeMatcher m = new DefaultNodeMatcher(ElementSelectors.or((e1, e2) -> {
            if (e1 == null || e2 == null) {
                return false;
            }
            return "expectedValue".equals(e1.getLocalName())
                && "value".equals(e2.getLocalName());
        }), ElementSelectors.byName);
    Diff d = DiffBuilder.compare(x1)
        .withTest(x2)
        .withNodeMatcher(m)
        .withDifferenceEvaluator(DifferenceEvaluators
            .downgradeDifferencesToEqual(ComparisonType.ELEMENT_TAG_NAME))
        .build();
    System.err.println(d);
}

将适用于简单的情况。

于 2018-03-07T06:27:34.783 回答