I need to compare XML files using XMLUnit 2
where xml subnodes can differ in order. Due to the underlying libraries that are used I can't influence order of subnodes.
For comparison I am using:
<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>
The problem boils down to this JUnit test:
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());
}
}
where t1.xml
contains:
<root>
<child>
<node1/>
</child>
<child>
<node2/>
</child>
</root>
and t2.xml
contains:
<root>
<child>
<node2/>
</child>
<child>
<node1/>
</child>
</root>
Actually, node1
and node2
are changed in order. The test result is:
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>
I'm wonder if it is possible to compare such xml files with XMLUnit 2
.
Any kind of help is appreciated.