I have two XML files:
<!------------------------File1--------------------------------->
<note id="ignoreThisAttribute_1">
<to>Experts</to>
<from>Matrix</from>
<heading id="dontIgnoreThisAttribute_1">Reminder</heading>
<body>Help me with this problem</body>
</note>
<!------------------------File2--------------------------------->
<note id="ignoreThisAttribute_2">
<to>Experts</to>
<from>Matrix</from>
<heading id="dontIgnoreThisAttribute_2">Reminder</heading>
<body>Help me with this problem</body>
</note>
I have to ignore the attribute:id of Node:note while comparing these two files.
I am using DiffBuilder:
Diff documentDiff = DiffBuilder.compare(srcFile).withTest(destFile).build()
Most online solutions suggested implementing DifferenceEvaluator:
Tried that as well, but this ignores all nodes with attribute id, whereas I want to ignore an attribute from a specific node:
public class IgnoreAttributeDifferenceEvaluator implements DifferenceEvaluator {
private String attributeName;
public IgnoreAttributeDifferenceEvaluator(String attributeName) {
this.attributeName = attributeName;
}
@Override
public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
if (outcome == ComparisonResult.EQUAL)
return outcome;
final Node controlNode = comparison.getControlDetails().getTarget();
System.out.println(controlNode.getNodeName());
if (controlNode instanceof Attr) {
Attr attr = (Attr) controlNode;
if (attr.getName().equals(attributeName)) {
return ComparisonResult.EQUAL;
}
}
return outcome;
}
}
Calling method in my Test class:
final Diff documentDiff = DiffBuilder.compare(src).withTest(dest)
.withDifferenceEvaluator(new IgnoreAttributeDifferenceEvaluator("id"))
.build();
Can someone suggest me a way I can achieve this using XMLUnit 2.x New to XMLUnit so please help accordingly.
Thanks in advance.
You could use a
DifferenceEvaluatorif you really wanted to. All you'd have to do was testing the name of theAttr's "owner element"'s name in addition to the name of the attribute itself.But XMLUnit 2.x offers a different solution to this:
AttributeFilter. The code won't be that different from theDifferenceEvaluatoryou've already got, but you won't be mixing concerns.or even shorter with a lambda in
withAttributeFilterwhen using Java8.