首页 文章

在Java中比较2个XML文档的最佳方法

提问于
浏览
181

我正在尝试编写一个应用程序的自动测试,它基本上将自定义消息格式转换为XML消息并将其发送到另一端 . 我有一组很好的输入/输出消息对,所以我需要做的就是发送输入消息并监听XML消息从另一端出来 .

当需要将实际输出与预期输出进行比较时,我遇到了一些问题 . 我的第一个想法就是对预期和实际消息进行字符串比较 . 这样做效果不好,因为我们拥有的示例数据并不总是一致地格式化,并且通常会有不同的别名用于XML命名空间(有时根本不使用命名空间 . )

我知道我可以解析两个字符串,然后遍历每个元素并自己进行比较,这不会太困难,但我觉得有一个更好的方法或我可以利用的库 .

所以,归结起来,问题是:

给定两个包含有效XML的Java字符串,您将如何确定它们在语义上是否等效?如果您有办法确定差异是什么,可以获得奖励积分 .

14 回答

  • 6

    听起来像XMLUnit的工作

    例:

    public class SomeTest extends XMLTestCase {
      @Test
      public void test() {
        String xml1 = ...
        String xml2 = ...
    
        XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences
    
        // can also compare xml Documents, InputSources, Readers, Diffs
        assertXMLEquals(xml1, xml2);  // assertXMLEquals comes from XMLTestCase
      }
    }
    
  • 3

    以下将使用标准JDK库检查文档是否相同 .

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    
    Document doc1 = db.parse(new File("file1.xml"));
    doc1.normalizeDocument();
    
    Document doc2 = db.parse(new File("file2.xml"));
    doc2.normalizeDocument();
    
    Assert.assertTrue(doc1.isEqualNode(doc2));
    

    normalize()是为了确保没有循环(技术上不会有任何循环)

    上面的代码将要求空格中的空格相同,因为它保留并评估它 . Java附带的标准XML解析器不允许您设置功能以提供规范版本或了解 xml:space 如果这将成为问题,那么您可能需要替换XML解析器(如xerces)或使用JDOM .

  • 6

    Xom有一个Canonicalizer实用程序,可以将您的DOM转换为常规形式,然后您可以进行字符串化和比较 . 因此,无论空白不规则或属性排序如何,您都可以对文档进行定期,可预测的比较 .

    这在具有专用可视字符串比较器(如Eclipse)的IDE中尤其有效 . 您可以直观地表示文档之间的语义差异 .

  • 0

    最新版本的XMLUnit可以帮助断言两个XML的工作是相同的 . 此案件可能还需要 XMLUnit.setIgnoreWhitespace()XMLUnit.setIgnoreAttributeOrder() .

    请参阅下面的XML单元使用的简单示例的工作代码 .

    import org.custommonkey.xmlunit.DetailedDiff;
    import org.custommonkey.xmlunit.XMLUnit;
    import org.junit.Assert;
    
    public class TestXml {
    
        public static void main(String[] args) throws Exception {
            String result = "<abc             attr=\"value1\"                title=\"something\">            </abc>";
            // will be ok
            assertXMLEquals("<abc attr=\"value1\" title=\"something\"></abc>", result);
        }
    
        public static void assertXMLEquals(String expectedXML, String actualXML) throws Exception {
            XMLUnit.setIgnoreWhitespace(true);
            XMLUnit.setIgnoreAttributeOrder(true);
    
            DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));
    
            List<?> allDifferences = diff.getAllDifferences();
            Assert.assertEquals("Differences found: "+ diff.toString(), 0, allDifferences.size());
        }
    
    }
    

    如果使用Maven,请将其添加到 pom.xml

    <dependency>
        <groupId>xmlunit</groupId>
        <artifactId>xmlunit</artifactId>
        <version>1.4</version>
    </dependency>
    
  • 1

    既然你说“语义等价”我认为你的意思是你想做的不仅仅是字面上验证xml输出是(字符串)等于,你想要的东西像

    <foo>这里的一些东西</ foo> </ code>

    <foo>这里的一些东西</ foo> </ code>

    读作同等的 . 最终,你要在重构消息的任何对象上定义“语义等价”是至关重要的 . 只需从消息中构建该对象,并使用自定义equals()来定义您要查找的内容 .

  • 19

    谢谢,我扩展了这个,试试这个......

    import java.io.ByteArrayInputStream;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    
    public class XmlDiff 
    {
        private boolean nodeTypeDiff = true;
        private boolean nodeValueDiff = true;
    
        public boolean diff( String xml1, String xml2, List<String> diffs ) throws Exception
        {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            dbf.setCoalescing(true);
            dbf.setIgnoringElementContentWhitespace(true);
            dbf.setIgnoringComments(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
    
    
            Document doc1 = db.parse(new ByteArrayInputStream(xml1.getBytes()));
            Document doc2 = db.parse(new ByteArrayInputStream(xml2.getBytes()));
    
            doc1.normalizeDocument();
            doc2.normalizeDocument();
    
            return diff( doc1, doc2, diffs );
    
        }
    
        /**
         * Diff 2 nodes and put the diffs in the list 
         */
        public boolean diff( Node node1, Node node2, List<String> diffs ) throws Exception
        {
            if( diffNodeExists( node1, node2, diffs ) )
            {
                return true;
            }
    
            if( nodeTypeDiff )
            {
                diffNodeType(node1, node2, diffs );
            }
    
            if( nodeValueDiff )
            {
                diffNodeValue(node1, node2, diffs );
            }
    
    
            System.out.println(node1.getNodeName() + "/" + node2.getNodeName());
    
            diffAttributes( node1, node2, diffs );
            diffNodes( node1, node2, diffs );
    
            return diffs.size() > 0;
        }
    
        /**
         * Diff the nodes
         */
        public boolean diffNodes( Node node1, Node node2, List<String> diffs ) throws Exception
        {
            //Sort by Name
            Map<String,Node> children1 = new LinkedHashMap<String,Node>();      
            for( Node child1 = node1.getFirstChild(); child1 != null; child1 = child1.getNextSibling() )
            {
                children1.put( child1.getNodeName(), child1 );
            }
    
            //Sort by Name
            Map<String,Node> children2 = new LinkedHashMap<String,Node>();      
            for( Node child2 = node2.getFirstChild(); child2!= null; child2 = child2.getNextSibling() )
            {
                children2.put( child2.getNodeName(), child2 );
            }
    
            //Diff all the children1
            for( Node child1 : children1.values() )
            {
                Node child2 = children2.remove( child1.getNodeName() );
                diff( child1, child2, diffs );
            }
    
            //Diff all the children2 left over
            for( Node child2 : children2.values() )
            {
                Node child1 = children1.get( child2.getNodeName() );
                diff( child1, child2, diffs );
            }
    
            return diffs.size() > 0;
        }
    
    
        /**
         * Diff the nodes
         */
        public boolean diffAttributes( Node node1, Node node2, List<String> diffs ) throws Exception
        {        
            //Sort by Name
            NamedNodeMap nodeMap1 = node1.getAttributes();
            Map<String,Node> attributes1 = new LinkedHashMap<String,Node>();        
            for( int index = 0; nodeMap1 != null && index < nodeMap1.getLength(); index++ )
            {
                attributes1.put( nodeMap1.item(index).getNodeName(), nodeMap1.item(index) );
            }
    
            //Sort by Name
            NamedNodeMap nodeMap2 = node2.getAttributes();
            Map<String,Node> attributes2 = new LinkedHashMap<String,Node>();        
            for( int index = 0; nodeMap2 != null && index < nodeMap2.getLength(); index++ )
            {
                attributes2.put( nodeMap2.item(index).getNodeName(), nodeMap2.item(index) );
    
            }
    
            //Diff all the attributes1
            for( Node attribute1 : attributes1.values() )
            {
                Node attribute2 = attributes2.remove( attribute1.getNodeName() );
                diff( attribute1, attribute2, diffs );
            }
    
            //Diff all the attributes2 left over
            for( Node attribute2 : attributes2.values() )
            {
                Node attribute1 = attributes1.get( attribute2.getNodeName() );
                diff( attribute1, attribute2, diffs );
            }
    
            return diffs.size() > 0;
        }
        /**
         * Check that the nodes exist
         */
        public boolean diffNodeExists( Node node1, Node node2, List<String> diffs ) throws Exception
        {
            if( node1 == null && node2 == null )
            {
                diffs.add( getPath(node2) + ":node " + node1 + "!=" + node2 + "\n" );
                return true;
            }
    
            if( node1 == null && node2 != null )
            {
                diffs.add( getPath(node2) + ":node " + node1 + "!=" + node2.getNodeName() );
                return true;
            }
    
            if( node1 != null && node2 == null )
            {
                diffs.add( getPath(node1) + ":node " + node1.getNodeName() + "!=" + node2 );
                return true;
            }
    
            return false;
        }
    
        /**
         * Diff the Node Type
         */
        public boolean diffNodeType( Node node1, Node node2, List<String> diffs ) throws Exception
        {       
            if( node1.getNodeType() != node2.getNodeType() ) 
            {
                diffs.add( getPath(node1) + ":type " + node1.getNodeType() + "!=" + node2.getNodeType() );
                return true;
            }
    
            return false;
        }
    
        /**
         * Diff the Node Value
         */
        public boolean diffNodeValue( Node node1, Node node2, List<String> diffs ) throws Exception
        {       
            if( node1.getNodeValue() == null && node2.getNodeValue() == null )
            {
                return false;
            }
    
            if( node1.getNodeValue() == null && node2.getNodeValue() != null )
            {
                diffs.add( getPath(node1) + ":type " + node1 + "!=" + node2.getNodeValue() );
                return true;
            }
    
            if( node1.getNodeValue() != null && node2.getNodeValue() == null )
            {
                diffs.add( getPath(node1) + ":type " + node1.getNodeValue() + "!=" + node2 );
                return true;
            }
    
            if( !node1.getNodeValue().equals( node2.getNodeValue() ) )
            {
                diffs.add( getPath(node1) + ":type " + node1.getNodeValue() + "!=" + node2.getNodeValue() );
                return true;
            }
    
            return false;
        }
    
    
        /**
         * Get the node path
         */
        public String getPath( Node node )
        {
            StringBuilder path = new StringBuilder();
    
            do
            {           
                path.insert(0, node.getNodeName() );
                path.insert( 0, "/" );
            }
            while( ( node = node.getParentNode() ) != null );
    
            return path.toString();
        }
    }
    
  • 34

    Tom 's answer, here'上构建使用XMLUnit v2的示例 .

    它使用这些maven依赖项

    <dependency>
            <groupId>org.xmlunit</groupId>
            <artifactId>xmlunit-core</artifactId>
            <version>2.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.xmlunit</groupId>
            <artifactId>xmlunit-matchers</artifactId>
            <version>2.0.0</version>
            <scope>test</scope>
        </dependency>
    

    ..这是测试代码

    import static org.junit.Assert.assertThat;
    import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
    import org.xmlunit.builder.Input;
    import org.xmlunit.input.WhitespaceStrippedSource;
    
    public class SomeTest extends XMLTestCase {
        @Test
        public void test() {
            String result = "<root></root>";
            String expected = "<root>  </root>";
    
            // ignore whitespace differences
            // https://github.com/xmlunit/user-guide/wiki/Providing-Input-to-XMLUnit#whitespacestrippedsource
            assertThat(result, isIdenticalTo(new WhitespaceStrippedSource(Input.from(expected).build())));
    
            assertThat(result, isIdenticalTo(Input.from(expected).build())); // will fail due to whitespace differences
        }
    }
    

    概述这个的文档是https://github.com/xmlunit/xmlunit#comparing-two-documents

  • 1

    斯卡弗曼似乎给出了一个很好的答案 .

    另一种方法可能是使用xmlstarlet(http://xmlstar.sourceforge.net/)等命令行实用程序格式化XML,然后格式化两个字符串,然后使用任何diff实用程序(库)来区分生成的输出文件 . 当问题与名称空间有关时,我不知道这是否是一个很好的解决方案 .

  • 182

    我正在使用Altova DiffDog,它可以选择在结构上比较XML文件(忽略字符串数据) .

    这意味着(如果选中'忽略文本'选项):

    <foo a="xxx" b="xxx">xxx</foo>
    

    <foo b="yyy" a="yyy">yyy</foo>
    

    在结构平等的意义上是平等的 . 如果您有不同数据但不是结构的示例文件,这很方便!

  • 2

    这将比较完整的字符串XML(在途中重新格式化它们) . 它使您可以轻松使用IDE(IntelliJ,Eclipse),因为您只需单击并直观地查看XML文件中的差异 .

    import org.apache.xml.security.c14n.CanonicalizationException;
    import org.apache.xml.security.c14n.Canonicalizer;
    import org.apache.xml.security.c14n.InvalidCanonicalizerException;
    import org.w3c.dom.Element;
    import org.w3c.dom.bootstrap.DOMImplementationRegistry;
    import org.w3c.dom.ls.DOMImplementationLS;
    import org.w3c.dom.ls.LSSerializer;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.TransformerException;
    import java.io.IOException;
    import java.io.StringReader;
    
    import static org.apache.xml.security.Init.init;
    import static org.junit.Assert.assertEquals;
    
    public class XmlUtils {
        static {
            init();
        }
    
        public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {
            Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
            byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());
            return new String(canonXmlBytes);
        }
    
        public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
            InputSource src = new InputSource(new StringReader(input));
            Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
            Boolean keepDeclaration = input.startsWith("<?xml");
            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
            LSSerializer writer = impl.createLSSerializer();
            writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
            return writer.writeToString(document);
        }
    
        public static void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
            String canonicalExpected = prettyFormat(toCanonicalXml(expected));
            String canonicalActual = prettyFormat(toCanonicalXml(actual));
            assertEquals(canonicalExpected, canonicalActual);
        }
    }
    

    我更喜欢这个XmlUnit,因为客户端代码(测试代码)更干净 .

  • 27

    AssertJ 1.4具有比较XML内容的特定断言:

    String expectedXml = "<foo />";
    String actualXml = "<bar />";
    assertThat(actualXml).isXmlEqualTo(expectedXml);
    

    这是Documentation

  • 0

    下面的代码适合我

    String xml1 = ...
    String xml2 = ...
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLAssert.assertXMLEqual(actualxml, xmlInDb);
    
  • -1

    将JExamXML与java应用程序一起使用

    import com.a7soft.examxml.ExamXML;
        import com.a7soft.examxml.Options;
    
           .................
    
           // Reads two XML files into two strings
           String s1 = readFile("orders1.xml");
           String s2 = readFile("orders.xml");
    
           // Loads options saved in a property file
           Options.loadOptions("options");
    
           // Compares two Strings representing XML entities
           System.out.println( ExamXML.compareXMLString( s1, s2 ) );
    
  • 1

    我需要与主要问题中请求的功能相同的功能 . 由于我不被允许使用任何第三方库,我已经基于@Archimedes Trajano解决方案创建了我自己的解决方案 .

    以下是我的解决方案 .

    import java.io.ByteArrayInputStream;
    import java.nio.charset.Charset;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.junit.Assert;
    import org.w3c.dom.Document;
    
    /**
     * Asserts for asserting XML strings.
     */
    public final class AssertXml {
    
        private AssertXml() {
        }
    
        private static Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns:(ns\\d+)=\"(.*?)\"");
    
        /**
         * Asserts that two XML are of identical content (namespace aliases are ignored).
         * 
         * @param expectedXml expected XML
         * @param actualXml actual XML
         * @throws Exception thrown if XML parsing fails
         */
        public static void assertEqualXmls(String expectedXml, String actualXml) throws Exception {
            // Find all namespace mappings
            Map<String, String> fullnamespace2newAlias = new HashMap<String, String>();
            generateNewAliasesForNamespacesFromXml(expectedXml, fullnamespace2newAlias);
            generateNewAliasesForNamespacesFromXml(actualXml, fullnamespace2newAlias);
    
            for (Entry<String, String> entry : fullnamespace2newAlias.entrySet()) {
                String newAlias = entry.getValue();
                String namespace = entry.getKey();
                Pattern nsReplacePattern = Pattern.compile("xmlns:(ns\\d+)=\"" + namespace + "\"");
                expectedXml = transletaNamespaceAliasesToNewAlias(expectedXml, newAlias, nsReplacePattern);
                actualXml = transletaNamespaceAliasesToNewAlias(actualXml, newAlias, nsReplacePattern);
            }
    
            // nomralize namespaces accoring to given mapping
    
            DocumentBuilder db = initDocumentParserFactory();
    
            Document expectedDocuemnt = db.parse(new ByteArrayInputStream(expectedXml.getBytes(Charset.forName("UTF-8"))));
            expectedDocuemnt.normalizeDocument();
    
            Document actualDocument = db.parse(new ByteArrayInputStream(actualXml.getBytes(Charset.forName("UTF-8"))));
            actualDocument.normalizeDocument();
    
            if (!expectedDocuemnt.isEqualNode(actualDocument)) {
                Assert.assertEquals(expectedXml, actualXml); //just to better visualize the diffeences i.e. in eclipse
            }
        }
    
    
        private static DocumentBuilder initDocumentParserFactory() throws ParserConfigurationException {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(false);
            dbf.setCoalescing(true);
            dbf.setIgnoringElementContentWhitespace(true);
            dbf.setIgnoringComments(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            return db;
        }
    
        private static String transletaNamespaceAliasesToNewAlias(String xml, String newAlias, Pattern namespacePattern) {
            Matcher nsMatcherExp = namespacePattern.matcher(xml);
            if (nsMatcherExp.find()) {
                xml = xml.replaceAll(nsMatcherExp.group(1) + "[:]", newAlias + ":");
                xml = xml.replaceAll(nsMatcherExp.group(1) + "=", newAlias + "=");
            }
            return xml;
        }
    
        private static void generateNewAliasesForNamespacesFromXml(String xml, Map<String, String> fullnamespace2newAlias) {
            Matcher nsMatcher = NAMESPACE_PATTERN.matcher(xml);
            while (nsMatcher.find()) {
                if (!fullnamespace2newAlias.containsKey(nsMatcher.group(2))) {
                    fullnamespace2newAlias.put(nsMatcher.group(2), "nsTr" + (fullnamespace2newAlias.size() + 1));
                }
            }
        }
    
    }
    

    它比较两个XML字符串,并通过将它们转换为两个输入字符串中的唯一值来处理任何不匹配的命名空间映射 .

    可以微调,即名称空间的翻译案例 . 但是根据我的要求,只做这项工作 .

相关问题