0

考虑:

<ParentTag>
    <Firstchild ID="id1" Title="title1">
        <secondchild ID="" Title="">
            <TagOfInterest ID="value1" Title=""/>
            <TagOfInterest ID="value2" Title=""/>
            <TagOfInterest ID="value3" Title=""/>
        </secondchild>
    </Firstchild>
</ParentTag>

和:

<secondxml>
    <something ID="id1" Title="title1">
        <anotherthing ID="" Title="">
            <TagOfInterest ID="value1" Title=""/>
            <TagOfInterest ID="dinosaur" Title=""/>
            <TagOfInterest ID="nomore" Title=""/>
        </anotherthing>
    </something>
</secondxml>

我正在使用 XML 单元,

要求 1:比较引擎应按标签名称“tagofInterest”进行比较。

要求 2:如果存在差异,则在该标签内按属性进行比较。

仅打印标签名称的实现,但对感兴趣的标签或内部属性的差异没有太多控制。在使用 XML Unit 的方式上有什么更好的建议吗?

        fr1 = new FileReader(expectedXML);
        fr2 = new FileReader(actualXML);
        Diff diff = new Diff(fr1, fr2);
        DetailedDiff detDiff = new DetailedDiff(diff);
        detDiff.overrideMatchTracker(new MatchTrackerImpl());
        detDiff.overrideElementQualifier(new ElementNameQualifier());
        detDiff.getAllDifferences();




class MatchTrackerImpl implements MatchTracker {
  public void matchFound(Difference difference) {
    if (difference != null) {
        NodeDetail controlNode = difference.getControlNodeDetail();
        NodeDetail testNode = difference.getTestNodeDetail();
        System.out.println(printNode(controlNode.getNode()));
        System.out.println(printNode(testNode.getNode()));
    }
}

private static String printNode(Node node) {
    if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
        StringWriter sw = new StringWriter();
        try {
            Transformer t = TransformerFactory.newInstance().newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            t.transform(new DOMSource(node), new StreamResult(sw));
        } catch (TransformerException te) {
            System.out.println("nodeToString Transformer Exception");
        }
        return sw.toString();

     }
    return null;
 }
}
4

1 回答 1

0

从您的示例中,我了解到“tagofInterest”作为 forrest 的一部分出现,而不是作为文档内的单个元素树。否则,您可以使用 XMLUnit 2.x 并且仅将 应用于感兴趣DifferenceEngineElements。

XMLUnit 中没有内置方法,您必须提供您自己的 XMLUnit 扩展点之一的实现。

您正在寻找的接口DifferenceListener在 XMLUnit 1.x 和DifferenceEvaluator2.x 中。这些负责确定是否应该报告引擎检测到的差异(如果是,那么它有多严重)。

您可以提供您自己的实现,该实现降级为未命名为“tagofInterest”的节点检测到的所有差异。如果您也对“tagofInterest”的孩子感兴趣,它可能会变得有点复杂,因为您需要向上查看是否有“tagofInterest”的父母。

于 2017-01-21T08:37:15.327 回答