首先感谢您提供这个很棒的图书馆,它真的很棒。
我在比较 xml 文档中不同顺序的元素时遇到问题。我开发了一个自定义 ElementSelector 以与 NodeMatcher 一起使用(稍后的代码),但它似乎仍然基于元素顺序而不是元素内容进行检查。让我写一个例子
控制
<Parent>
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Email>johndoe@email.com</Email>
</Person>
<Person>
<FirstName>Mickey</FirstName>
<LastName>Mouse</LastName>
<Email>mm@email.com</Email>
</Person>
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Email />
</Person>
</Parent>
测试
<Parent>
<Person>
<FirstName>Mickey</FirstName>
<LastName>Mouse</LastName>
<Email>mm@email.com</Email>
</Person>
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Email>johndoe@email.com</Email>
</Person>
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Email />
</Person>
</Parent>
我是如何制作差异的
Diff diff = DiffBuilder.compare(refSource)
.withTest(testSource)
.checkForSimilar()
.ignoreWhitespace()
.normalizeWhitespace()
.withNodeMatcher(new DefaultNodeMatcher(selector))
.build();
我是如何创建 ElementSelector 选择器的
ElementSelector selector = ElementSelectors.conditionalBuilder()
.whenElementIsNamed("Person").thenUse(new PersonNodeMatcher())
.defaultTo(ElementSelectors.byNameAndText).build();
PersonNodeMatcher 实际是如何实现的
public class PersonNodeMatcher extends BaseElementSelector {
@Override
protected boolean canBeCompared(Element control, Element test) {
String controlFirstName = control.getElementsByTagName("FirstName").item(0).getTextContent();
String controlLastName = control.getElementsByTagName("LastName").item(0).getTextContent();
Node controlEmailNode = control.getElementsByTagName("Email").item(0);
String controlEmail = null;
if ( controlEmailNode != null) {
controlEmail = controlEmailNode.getTextContent();
}
String testFirstName = test.getElementsByTagName("FirstName").item(0).getTextContent();
String testLastName = test.getElementsByTagName("LastName").item(0).getTextContent();
Node testEmailNode = test.getElementsByTagName("Email").item(0);
String testEmail = null;
if (testEmailNode != null) {
testEmail = testEmailNode.getTextContent();
}
return bothNullOrEqual(controlFirstName,testFirstName) &&
bothNullOrEqual(controlLastName,testLastName) &&
bothNullOrEqual(controlEmail,testEmail);
}
该例程仍在按顺序检查节点,因此它们永远不会匹配。我认为提供一个节点自定义节点匹配器,我将能够使用提供的 tagName 检查所有元素。
我做错了什么还是根本不可能?
[更新] 使用 alpha3 我必须对代码进行一些修改,特别是:
ElementSelector selector = ElementSelectors.conditionalBuilder()
.whenElementIsNamed("Person").thenUse(new PersonNodeMatcher()).build();
Diff diff = DiffBuilder.compare(refSource)
.withTest(testSource)
.checkForSimilar()
.ignoreWhitespace()
.normalizeWhitespace()
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.or(selector,ElementSelectors.Default)))
.build();