how to compare prefixed with no prefix xml documents in xmlunit to get similar result

89 views Asked by At

xmlnit does not recognize the following two xml "identical" (except one has defined namespace) documents to be similar:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:message xmlns:ns3="https://www.bookmarks.dev/xml/bookmarks">
    <ns3:bookmarks>
        <ns3:bookmark>
            <ns3:name>Bookmarks and Snippets Manager</ns3:name>
            <ns3:url>https://www.bookmarks.dev</ns3:url>
        </ns3:bookmark>
    </ns3:bookmarks>
</ns3:message>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<message>
    <bookmarks>
        <bookmark>
            <name>Bookmarks and Snippets Manager</name>
            <url>https://www.bookmarks.dev</url>
        </bookmark>
    </bookmarks>
</message>

The failing unit test comparing the two:

  @Test
  void givenSameMessageOneWithoutNamespace_shouldBeSimilar() {
    ClassLoader classLoader = getClass().getClassLoader();
    final var withNamespaceInput =
        Input.from(
            new File(classLoader.getResource("with-namespace.xml").getFile()));
    final var noNamespaceInput =
        Input.from(
            new File(
                classLoader
                    .getResource("no-namespace.xml")
                    .getFile()));

    final Diff documentDiff =
            DiffBuilder.compare(withNamespaceInput)
                    .withTest(noNamespaceInput)
                    .checkForSimilar()
                    .build();

    assertThat(documentDiff.hasDifferences()).isFalse();
  }

The differences come in the form Expected namespace uri 'null' but was 'https://www.bookmarks.dev/xml/bookmarks' - comparing <message...> at /message[1] to <ns3:message...> at /message[1] (DIFFERENT)...

Any ideas how can I configure the comparator to ignore the missing prefix in the second document?

1

There are 1 answers

0
ama On

My problem was that when generating the no-namespace document I had no default namespace defined in the root element. Adding it solves the problem and xmlunit recognizes them as similar:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<message xmlns="https://www.bookmarks.dev/xml/bookmarks">
    <bookmarks>
        <bookmark>
            <name>Bookmarks and Snippets Manager</name>
            <url>https://www.bookmarks.dev</url>
        </bookmark>
    </bookmarks>
</message>