1

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

最好的问候, 凯沙夫

4

1 回答 1

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"));
于 2014-10-17T14:36:24.713 回答