简体   繁体   English

使用XMLUnit通过跳过一些TAG的一些属性来比较两个XML

[英]Compare two XML using XMLUnit by skipping few attributes of some TAGs

I'm working on this java API(XMLUuit.jar) from last few days. 最近几天,我正在研究此Java API(XMLUuit.jar)。 I want to compare two XML files by skipping few parameters of a XML tag using XMLUnit API. 我想通过使用XMLUnit API跳过XML标记的几个参数来比较两个XML文件。

<emp>
  <name id="1">xyz</name>
</emp>
<emp>
  <name id="2">xyz</name>
</emp>

these two files are same if i skip the comparison of id attribute. 如果我跳过id属性的比较,这两个文件是相同的。 i have some scenarios where requirements are like this. 我有一些需求是这样的情况。 Any suggestions ???? 有什么建议么 ????

In order to suppress certain differences you implement a DifferenceEvaluator 为了抑制某些差异,您实现了DifferenceEvaluator

import org.w3c.dom.Attr;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.*;
import org.xmlunit.util.Nodes;

public class AttributesTest {

    public static void main(String[] args) {
        Diff d = DiffBuilder.compare("<emp>\n" +
                                     "  <name id=\"1\">xyz</name>\n" +
                                     "</emp>")
            .withTest("<emp>\n" +
                      "  <name id=\"2\">xyz</name>\n" +
                      "</emp>")
            .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
            .withDifferenceEvaluator((comparison, outcome) -> {
                    if (outcome != ComparisonResult.EQUAL && comparison.getType() == ComparisonType.ATTR_VALUE) {
                        Attr a = (Attr) comparison.getControlDetails().getTarget();
                        if ("id".equals(Nodes.getQName(a).getLocalPart())
                            && "name".equals(Nodes.getQName(a.getOwnerElement()).getLocalPart())) {
                            return ComparisonResult.EQUAL;
                        }
                    }
                    return outcome;
                })
            .build();
        System.err.println("Differences? " + d.hasDifferences());
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM