在将XML文档与XMLUnit进行比较时,忽略几个孩子进行比较

时间:2010-09-16 12:24:58

标签: xml comparison xmlunit

在将XML文档与XMLUnit进行比较时,是否可以忽略元素中的一些子元素?我想在比较它时忽略元素中的任何空文本节点。

最诚挚的问候, 凯沙夫

1 个答案:

答案 0 :(得分:1)

您可以使用此侦听器:

import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceConstants;
import org.custommonkey.xmlunit.DifferenceListener;
import org.w3c.dom.Node;

import java.util.HashSet;
import java.util.Set;

public class IgnoreChildrenOfNamedElementsDifferenceListener implements DifferenceListener {
    public IgnoreChildrenOfNamedElementsDifferenceListener() {}

    public int differenceFound(Difference difference) {
        if (difference.getId() == DifferenceConstants.HAS_CHILD_NODES_ID ||
                difference.getId() == DifferenceConstants.CHILD_NODELIST_LENGTH_ID ||
                difference.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID) {
                return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
            }
        }    
        return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
    }

    @Override
    public void skippedComparison(Node control, Node test) {}
}

然后你可以按照以下方式使用它:

Diff diff = new Diff(expectedDoc, obtainedDoc);
diff.overrideDifferenceListener(new IgnoreChildrenOfNamedElementsDifferenceListener("TestDateTime"));