java 如何使用java比较和获取两个xml文件之间的差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34410803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:52:33  来源:igfitidea点击:

How to compare and get difference between two xml files using java?

javaxmlparsingdom

提问by Ilavarasan Jayaraman

I have two xml files as below.

我有两个 xml 文件,如下所示。

Compare.xml

比较.xml

<?xml version="1.0"?>
<class>
<student rollno="393">
  <firstname>dinkar</firstname>
  <lastname>kad</lastname>
  <nickname>dinkar</nickname>
  <marks>85</marks>
</student>
<student rollno="493">
  <firstname>Vaneet</firstname>
  <lastname>Gupta</lastname>
  <nickname>vinni</nickname>
  <marks>95</marks>
</student>
</class>

Reference.xml

参考.xml

<?xml version="1.0"?>
<class>
<student rollno="393">
  <firstname>ila</firstname>
  <lastname>kad</lastname>
  <nickname>dinkar</nickname>
  <marks>85</marks>
</student>
<student rollno="493">
  <firstname>Vaneet</firstname>
  <lastname>Gupta</lastname>
  <nickname>vinni</nickname>
  <marks>95</marks>
</student>
</class>

Now I need to compare and get the difference between these two xml files. I also need the output to be exported as a log file.

现在我需要比较并获得这两个 xml 文件之间的差异。我还需要将输出导出为日志文件。

Below my code:

在我的代码下面:

package DomParserDemo;
import java.io.File;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class DomParserDemo {
public static void main(String[] args){

  try { 
     File inputFile = new File("input.txt");
     DocumentBuilderFactory dbFactory 
        = DocumentBuilderFactory.newInstance();
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
     Document doc = dBuilder.parse(inputFile);
     doc.getDocumentElement().normalize();
     System.out.println("Root element :" 
        + doc.getDocumentElement().getNodeName());
     NodeList nList = doc.getElementsByTagName("student");
     System.out.println("----------------------------");
     for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        System.out.println("\nCurrent Element :" 
           + nNode.getNodeName());
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
           Element eElement = (Element) nNode;
           System.out.println("Student roll no : " 
              + eElement.getAttribute("rollno"));
           System.out.println("First Name : " 
              + eElement
              .getElementsByTagName("firstname")
              .item(0)
              .getTextContent());
           System.out.println("Last Name : " 
           + eElement
              .getElementsByTagName("lastname")
              .item(0)
              .getTextContent());
           System.out.println("Nick Name : " 
           + eElement
              .getElementsByTagName("nickname")
              .item(0)
              .getTextContent());
           System.out.println("Marks : " 
           + eElement
              .getElementsByTagName("marks")
              .item(0)
              .getTextContent());
        }
     }

     FileHandler handler = new FileHandler("logfile.log");

     // Add to the desired logger
     Logger logger = Logger.getLogger("");
     logger.addHandler(handler);
     System.out.println("Log Generated Successfully...!!!");


  } catch (Exception e) {
      System.out.println("Log Generation Failed..!!!");
     e.printStackTrace();
  }
}

}

Now I can see the xml files in output with out tags and i need its difference and the output should be exported as a log file.

现在我可以在输出中看到带有 out 标签的 xml 文件,我需要它的差异,输出应该作为日志文件导出。

Kindly help me to finish this and thanks in advance.

请帮我完成这个,并提前致谢。

回答by dstronczak

回答by Ilavarasan Jayaraman

Thank you. My present code: package compare5;

谢谢你。我现在的代码:包 compare5;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.custommonkey.xmlunit.DetailedDiff; 
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.xml.sax.SAXException;

public class ComparisonTest {

final static Logger logger = Logger.getLogger(ComparisonTest.class);

public static void main(String[] args) {
File f1 = new File("D:/reference.xml");
File f2= new File("D:/comparison.xml");
File f3= new File("D:/Activity log.log");

try {
                            //create a new file if it doesn't 
             f3.createNewFile();

    } catch (IOException e) {

                    e.printStackTrace();
                             }
FileReader fr1 = null;
FileReader fr2 = null;
try {
fr1 = new FileReader(f1);
fr2 = new FileReader(f2);
} catch (FileNotFoundException e) {
e.printStackTrace();
                                  }

try {
Diff diff = new Diff(fr1, fr2);
System.out.println("Similar? " + diff.similar());
System.out.println("Identical? " + diff.identical());

DetailedDiff detDiff = new DetailedDiff(diff);
List differences = detDiff.getAllDifferences();
for (Object object : differences) {
    Difference difference = (Difference)object;
    System.out.println("***********************");
    System.out.println(difference);
    System.out.println("***********************");
  }

 } catch (SAXException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }


 ComparisonTest obj = new ComparisonTest();
 obj.runMe("ila");


}

 private void runMe(String parameter){



if(logger.isDebugEnabled()){
    logger.debug("This is debug : " + parameter);
}

if(logger.isInfoEnabled()){
    logger.info("This is info : " + parameter);
}

logger.warn("This is warn : " + parameter);
logger.error("This is error : " + parameter);
logger.fatal("This is fatal : " + parameter);



}






} 

回答by Aguid

try this

试试这个

  private void compare(File file1, File file2) throws Exception {
    List<String> list1 = Files.lines(Paths.get(file1.getPath())).collect(Collectors.toList());
    List<String> list2 = Files.lines(Paths.get(file2.getPath())).collect(Collectors.toList());
    list1.stream().filter(s -> !list2.contains(s)).peek(System.out::println).count() != 0;
    list2.stream().filter(s -> !list1.contains(s)).peek(System.out::println).count() != 0;
}

回答by user2885129

Above Solution Worked for me with a slight change :

以上解决方案对我有用,略有变化:

private static List<String> compareXMLLineByLine(File file1, File file2) throws Exception {
    List<String> list1 = Files.lines(Paths.get(file1.getPath())).collect(Collectors.toList());
    List<String> list2 = Files.lines(Paths.get(file2.getPath())).collect(Collectors.toList());

    return list1.stream().filter(s->!list2.contains(s)).peek(s -> System.out.println("mismatched value: " + s)).collect(Collectors.toList());  
}