9

I have 2 xml files:

The problem is in attributes prefixes.

<element xmlns:prefix1="namespace" prefix1:attribute="some value">Some text</element>


<element xmlns:prefix2="namespace" prefix2:attribute="some value">Some text</element>

these two xml are the same, with the same namespace, but with different prefixes. If I compare with xmlunit -> assertion fails. How can I handle it?

in case of similar() or identical() comparison I have error:

Expected attribute name 'message:MessageNameString' but was 'null'
Expected attribute name 'message:MessageVersion' but was 'null'
Expected attribute name 'null' but was 'mes:MessageNameString'
Expected attribute name 'null' but was 'mes:MessageVersion'

Constantine Gladky
  • 1,245
  • 6
  • 27
  • 45
  • Are you able to provide the actual XML you are testing? Even when I add attributes the "similar" check passes for me. – Nick Wilson Nov 13 '12 at 13:31
  • I can send it in e-mail. They are rather huge for stackoverflow's forms – Constantine Gladky Nov 13 '12 at 13:39
  • XML defines "identicalness" — it should be possible to define a "similar" based on the XML definition of similar. e.g. `` and `` are semantically the same document. Using "similar()" is problematic if child order is important (it often is). Shucks! – mogsie Jun 13 '14 at 08:58

3 Answers3

6

The following test passes the "similar" check but fails the "identical" check:

    String control = "<prefix1:element xmlns:prefix1=\"namespace\" prefix1:attribute=\"x\">Some text</prefix1:element>";
    String test = "<prefix2:element xmlns:prefix2=\"namespace\" prefix2:attribute=\"x\">Some text</prefix2:element>";
    try
    {
        Diff diff = XMLUnit.compareXML( control, test );
        assertTrue( "Similar", diff.similar() );
        assertTrue( "Identical", diff.identical() );
    }
    catch ( Exception e )
    {
        fail( e.getMessage() );
    }

From the xmlunit API docs:

  • identical: the content and sequence of the nodes in the documents are exactly the same
  • similar: the content of the nodes in the documents are the same, but minor differences exist e.g. sequencing of sibling elements, values of namespace prefixes, use of implied attribute values

So using the "similar" check should give you what you want.

Edit: added prefixed attributes, same result.

Nick Wilson
  • 4,959
  • 29
  • 42
0
// identical
XMLAssert.assertXMLEqual(XMLUnit.compareXML(control, test), true)
// similar
XMLAssert.assertXMLEqual(XMLUnit.compareXML(control, test), false)
Vadzim
  • 24,954
  • 11
  • 143
  • 151
0

With XMLUnit 1.x:

// Similar
XMLAssert.assertXMLEqual()

// Identical
XMLAssert.assertXMLIdentical()

With XMLUnit 2.x:

import static org.xmlunit.assertj.XmlAssert.assertThat;
...

// Similar
assertThat(xmlResult).and(xmlExpected).areSimilar();

// Identical
assertThat(xmlResult).and(xmlExpected).areIdentical();

See https://github.com/xmlunit/xmlunit#comparing-two-documents

leaqui
  • 533
  • 6
  • 22