【问题标题】:How to compare and get difference between two xml files using java?java - 如何使用java比较和获取两个xml文件之间的差异?
【发布时间】:2016-03-28 10:05:03
【问题描述】:

我有两个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 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 文件,我需要它的区别,并且输出应该导出为日志文件。

请帮助我完成此操作并提前致谢。

【问题讨论】:

  • 您可以使用xpath 根据一个文档中的节点生成查询并查询另一个文档,如果查询没有返回匹配结果,则您知道您的第一个节点中有一个节点这不会出现在你的第二个。您可以对两个文档都这样做

标签: java xml parsing dom


【解决方案1】:

上述解决方案对我有用,但稍作改动:

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

【讨论】:

    【解决方案2】:

    【讨论】:

    • 谢谢。导出为日志文件时仍有问题。
    【解决方案3】:

    谢谢。 我现在的代码: 包比较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);
    
    
    
    }
    
    
    
    
    
    
    } 
    

    【讨论】:

      【解决方案4】:

      试试这个

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-07
        • 2012-12-25
        • 2018-09-14
        • 1970-01-01
        • 2017-02-14
        • 2021-05-22
        • 1970-01-01
        • 2016-10-27
        相关资源
        最近更新 更多