Search code examples
javaxmlcomparisonxmlunitxmlunit-2

Is there any way to get the node name when comparing the attribute value of a node inside DifferenceEvaluator?


I'm using org.xmlunit 2.9 in java to compare two XMLs but there are certain exceptions for comparison (example: If XML1 contains a node <version value="12.3" /> and XML2 contains a node <version value="12.345" />, then it should set the result to EQUAL). To handle these exceptions I'm using DifferenceEvaluator but I don't want to rely on the value of the node I want to check whether node name is 'version' when comparing the values.

This is what my DifferenceEvaluator code looks like:

DifferenceEvaluator ResponseEvaluator = new DifferenceEvaluator() {
           public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
                if(outcome != ComparisonResult.EQUAL) {                 
                    if(comparison.getControlDetails().getValue() != null && comparison.getTestDetails().getValue() != null && comparison.getControlDetails().getValue().toString().equals("12.3")) {
                            if(comparison.getType() != null 
                                    && comparison.getType() == ComparisonType.ATTR_VALUE 
                                    && comparison.getTestDetails().getValue().toString().contains("12")) {
                                return ComparisonResult.EQUAL;
                            }
                      }
                 }
            }
}

Here, instead of comparison.getControlDetails().getValue().toString().equals("12.3") I want to use something like comparison.getControlDetails().getNodeName.equals("version") and then proceed with comparing the attribute value. Is it possible to achieve this?


Solution

  • You can fetch the node name of the attribute being compared by using getOwnerElement() method. Here's a sample code:

    Node controlNode = comparison.getControlDetails().getTarget();
    if(controlNode instanceof Attr) {
        Attr nodeAttribute = (Attr) controlNode;
        String nodeName = nodeAttribute.getOwnerElement().getNodeName();
        if(nodeName.equals("version")) {
            // your custom comparison code
        }
    }
    

    Here's the documentation you can refer from to add more customaisation https://github.com/xmlunit/user-guide/wiki/DifferenceEvaluator