如何使用java比较两个xml文件并获得差异?

时间:2015-12-22 07:44:58

标签: java xml parsing dom

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

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>

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

在我的代码下面:

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

}

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

请帮助我完成此事并提前感谢。

4 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

谢谢。 我现在的代码:     包比较5;

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



}






} 

答案 2 :(得分:0)

试试这个

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

答案 3 :(得分:0)

以上解决方案为我工作,但有一些细微变化:

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