两个xml比较并得到差异

时间:2017-08-07 11:27:36

标签: xml comparison

我的代码是:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.XMLUnit;
import org.xml.sax.SAXException;

public class XmlCompare {

    public static void main(String args[]) throws FileNotFoundException, SAXException,
    IOException { 

        // reading two xml file to compare in Java program 
        FileInputStream fis1 = new FileInputStream("D:/SasmitaDas/xml/source.xml"); 
        FileInputStream fis2 = new FileInputStream("D:/SasmitaDas/xml/target.xml"); 
        // using BufferedReader for improved performance 
        BufferedReader source = new BufferedReader(new InputStreamReader(fis1)); 
        BufferedReader target = new BufferedReader(new InputStreamReader(fis2)); 
        //configuring XMLUnit to ignore white spaces 
        XMLUnit.setIgnoreWhitespace(true); 
        //comparing two XML using XMLUnit in Java 
        List differences = compareXML(source, target); 
        //showing differences found in two xml files 
        printDifferences(differences); 
        } 

    public static List compareXML(Reader source, Reader target) throws  SAXException, 
    IOException{

        //creating Diff instance to compare two XML files 
        Diff xmlDiff = new Diff(source, target); 
        //for getting detailed differences between two xml files 
        DetailedDiff detailXmlDiff = new DetailedDiff(xmlDiff); 
        return detailXmlDiff.getAllDifferences(); 
        }

    public static void printDifferences(List differences){ 

        int totalDifferences = differences.size(); 
        System.out.println("===============================");
        System.out.println("Total differences : " + totalDifferences);
        System.out.println("================================");
        for(Object difference : differences){
            System.out.println(difference); 
            }
        } 
    }

我收到的错误是:

  

[致命错误]:1:1:prolog中不允许内容。   线程“main”org.xml.sax.SAXParseException中的异常;电话号码:   1; columnNumber:1;序言中不能有内容。在   org.apache.xerces.parsers.DOMParser.parse(未知来源)at   org.apache.xerces.jaxp.DocumentBuilderImpl.parse(未知来源)at   org.custommonkey.xmlunit.XMLUnit.buildDocument(XMLUnit.java:382)at at   org.custommonkey.xmlunit.XMLUnit.buildDocument(XMLUnit.java:369)at at   org.custommonkey.xmlunit.Diff。(Diff.java:101)at   seleniumCode.XmlCompare.compareXML(XmlCompare.java:39)at   seleniumCode.XmlCompare.main(XmlCompare.java:30)

     

请帮助解决此问题

1 个答案:

答案 0 :(得分:0)

错误在您的XML文件中,代码

没有问题