有没有任何方法可以比较两个xml,它应该忽略确切的内容文本,但应该按数据类型比较内容文本



我尝试了下面的例子,并尝试了DiffBuilderCompareMatcher类的不同方法:

import org.junit.jupiter.api.Test;
import org.xmlunit.diff.DefaultNodeMatcher;
import org.xmlunit.diff.ElementSelectors;
import org.xmlunit.matchers.CompareMatcher;
import static org.hamcrest.MatcherAssert.assertThat;
public class XmlDemo4 {
@Test
public void demoMethod() {
String actual = "<struct><int>3</int><boolean>false</boolean></struct>";
String expected = "<struct><boolean>false</boolean><int>4</int></struct>";
assertThat(actual, CompareMatcher.isSimilarTo(expected)
.ignoreWhitespace().normalizeWhitespace().
withNodeMatcher(new 
DefaultNodeMatcher(ElementSelectors.byName,ElementSelectors.Default)));
}
}

通过运行上面的代码,我得到:

java.lang.AssertionError: 
Expected: Expected text value '4' but was '3' - comparing <int ...>4</int> at 
/struct[1]/int[1]/text()[1] to <int ...>3</int> at /struct[1]/int[1]/text()[1]:
<int>4</int>
but: result was: 
<int>3</int>
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
at StringXml.XmlDemo4.demoMethod(XmlDemo4.java:29)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
Process finished with exit code -1

这里它也在比较内容文本,请建议,有什么方法可以将内容文本与数据类型进行比较吗?它不应该与确切的内容文本进行比较

您需要一些XML diff的实现。我不知道Java,但有一些python库:https://pypi.org/project/xmldiff/

另请参阅是否有可用的免费Xml Diff/Merge工具?

DifferenceEvaluator是决定差异是SIMILAREQUAL还是DIFFERENT的类。在我的方法中,我是说,如果有任何类型为TEXT的比较,那么将这些比较的结果作为SIMILAR请参阅XMLUnit 2.x

import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.*;
import static org.xmlunit.diff.ComparisonType.TEXT_VALUE;
public class XmlDemo {
public static void main(String[] args) {
String actual = "<struct><int>6</int><boolean>false</boolean></struct>";
String expected = "<struct><boolean>false</boolean><int>4</int></struct>";
Diff diff = DiffBuilder.compare(actual)
.checkForSimilar()
.withTest(expected)
.ignoreWhitespace().normalizeWhitespace()
.withNodeMatcher(new
DefaultNodeMatcher(ElementSelectors.byName))
.withDifferenceEvaluator(DifferenceEvaluators.chain(DifferenceEvaluators.Default, DifferenceEvaluators.downgradeDifferencesToSimilar(TEXT_VALUE)))
.build();
for (Difference difference: diff.getDifferences())
System.out.println(difference);
}

}

最新更新