【发布时间】:2015-11-28 19:24:59
【问题描述】:
我需要使用 XMLUnit 2 比较 XML 文件,其中 xml 子节点的顺序可能不同。由于使用了底层库,我无法影响子节点的顺序。
为了比较,我正在使用:
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-core</artifactId>
<version>2.0.0-alpha-02</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-matchers</artifactId>
<version>2.0.0-alpha-02</version>
<scope>test</scope>
</dependency>
问题归结为这个 JUnit 测试:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.builder.Input.fromString;
import static org.xmlunit.diff.ElementSelectors.byName;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.xmlunit.diff.DefaultNodeMatcher;
import java.io.IOException;
public class XmlTest {
@Test
public void test() throws Exception {
String t1 = fromClassPath("t1.xml");
String t2 = fromClassPath("t2.xml");
assertThat(fromString(t1), isSimilarTo(fromString(t2)).withNodeMatcher(new DefaultNodeMatcher(byName)));
}
private static String fromClassPath(String fileName) throws IOException {
return IOUtils.toString(new ClassPathResource(fileName).getInputStream());
}
}
其中t1.xml 包含:
<root>
<child>
<node1/>
</child>
<child>
<node2/>
</child>
</root>
而t2.xml 包含:
<root>
<child>
<node2/>
</child>
<child>
<node1/>
</child>
</root>
其实node1和node2是按顺序变化的。测试结果是:
java.lang.AssertionError:
Expected: Expected child 'node2' but was 'null' - comparing <node2...> at /root[1]/child[1]/node2[1] to <NULL>:
<node2/>
but: result was:
<NULL>
我想知道是否可以将此类 xml 文件与XMLUnit 2 进行比较。
任何形式的帮助表示赞赏。
【问题讨论】: