我正在使用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
或者最终忽略这种特定的比较。
有什么想法吗? 谢谢
答案 0 :(得分:0)
这简化了XML中相等的概念: - )
您需要做两件事,首先您需要提供自己的ElementSelector
,告诉XMLUnit甚至比较expectedValue
和value
节点。在第二部分中,您需要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)));