比较XML时如何映射/忽略某些标记?

时间:2018-03-06 15:02:54

标签: xml xmlunit-2

我正在使用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>

我正在寻找一种方法来向diffBuilder说expectedValue == value或者最终忽略这种特定的比较。

有什么想法吗? 谢谢

2 个答案:

答案 0 :(得分: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);
}

将适用于简单的案例。

答案 1 :(得分: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)));