Compare two XML strings ignoring element order

前端 未结 8 1591
陌清茗
陌清茗 2020-12-15 17:23

Suppose I have two xml strings


  a
  b



  b

        
相关标签:
8条回答
  • 2020-12-15 17:49

    XMLUnit will do what you want, but you have to specify the elementQualifier. With no elementQualifier specified it will only compare the nodes in the same position.

    For your example you want an ElementNameAndTextQualifer, this considers a node similar if one exists that matches the element name and it's text value, something like :

    Diff diff = new Diff(control, toTest);
    // we don't care about ordering
    diff.overrideElementQualifier(new ElementNameAndTextQualifier());
    XMLAssert.assertXMLEqual(diff, true);
    

    You can read more about it here: http://xmlunit.sourceforge.net/userguide/html/ar01s03.html#ElementQualifier

    0 讨论(0)
  • 2020-12-15 17:53

    I don't know what versions they took for the solutions, but nothing worked (or was simple at least) so here's my solution for who had the same pains.

    P.S. I hate people to miss the imports or the FQN class names of static methods

        @Test
    void given2XMLS_are_different_elements_sequence_with_whitespaces(){
        String testXml = "<struct><int>3</int>  <boolean>false</boolean> </struct>";
        String expected = "<struct><boolean>false</boolean><int>3</int></struct>";
    
        XmlAssert.assertThat(testXml).and(expected)
                .ignoreWhitespace()
                .normalizeWhitespace()
                .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))
                .areSimilar();
    }
    
    0 讨论(0)
提交回复
热议问题