有没有办法完全忽略 XMLUnit 中的空标签,以便在比较时不考虑它? 例如:
<a>
<b/>
<c>data1</c>
<d>data2</d>
</a>
和
<a>
<c>data1</c>
<d>data2</d>
</a>
不应返回任何差异。 是否有任何内置函数可以执行此操作? 谢谢。
最佳答案
一般来说,空标签与缺失标签不同,这就是 XMLUnit 提示的原因。在 XMLUnit 2.x 中,您可以使用 NodeFilter
抑制节点的比较。 NodeFilter
是一个谓词函数,它接受单个 DOM Node
并在比较文档时应考虑该节点时返回 true
。默认实现只是为所有不是文档类型声明的 Node
返回 true
。
您可以使用类似以下(未经测试)的类
class SuppressEmptyElements implements Predicate<Node> {
@Override
public boolean test(Node n) {
if (n instanceof Element) {
return !isEmpty((Element) n);
}
// not an element - a commment, nested text and so on
return true;
}
private boolean isEmpty(Element e) {
return e.getAttributes().getLength() == 0 && e.getChildNodes().getLength() == 0;
}
}
当使用DiffBuilder
时,你会使用withNodeFilter(new SuppressEmptyElements())
之类的东西。更长的故事可以在 XMLUnit 的 user guide 中找到。 .
关于java - 忽略 xmlunit 中的空标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50903514/