简体   繁体   中英

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

I have two xml files as below.

Compare.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 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.

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.

Kindly help me to finish this and thanks in advance.

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());  
}

Thank you. My present code: package 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);



}






} 

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM