2017-10-06 156 views
1

我想比较两个XML文件。我的要求是比较旧的和新的XML文件,如果有任何区别,将它合并到新的XML文件。比较两个xml文件并获得差异

下面的代码片段给了我两个文件是否相等。

public static void compare() throws SAXException, IOException, ParserConfigurationException{ 
    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("old.xml")); 
    doc1.normalizeDocument(); 

    Document doc2 = db.parse(new File("new.xml")); 
    doc2.normalizeDocument(); 

    System.out.println (doc1.isEqualNode(doc2)); 
} 

但我想要的差异也。请告诉我如何才能找到差异。

我已经试过XMLUnit,但我不想使用它。

回答

0

您可以使用jaxb解析您的xml并使用unmarshall方法构造java对象并比较您生成的对象。

见这里:How to compare jaxb, object, string to find differences

您也可以使用谷歌的diff匹配补丁API将两个XML比较字符串和补丁以创建新的。

https://code.google.com/archive/p/google-diff-match-patch/

DIFF演示:https://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html 补丁演示:https://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_patch.html

源可用在github:https://github.com/GerHobbelt/google-diff-match-patch

+0

在我的情况的XML是在不同的格式: .... ...,我有这样的多个标签。 –

+0

有没有什么办法在java本身来实现这一点。我不想使用第三方api。不能使用DocumentBuilderFactory? –

+0

不要重新发明轮子,要制作两个文件的差异并不那么容易。我认为这是使用经过测试和优秀API的最佳选择。 –