I need to compare two XML files and print the results in another xml files This code compares and print the differences in the console correctly,but it prints only one line in the XML file.Moreover when I view the output in the console,it seems it is creating n number of xml files equal to the totaldifferences. Any help is appreciated.Thanks in advance.
public class CreateXMLFileJava {
public static final String xmlFilePath = "C:\\test\\xmlfile.xml";
public static void main(String argv[]) throws SAXException, IOException, ParserConfigurationException, TransformerException
{
FileInputStream fis1 = new FileInputStream("c:\\test\\source.xml");
FileInputStream fis2 = new FileInputStream("c:\\test\\target.xml");
BufferedReader source = new BufferedReader(new InputStreamReader(fis1));
BufferedReader target = new BufferedReader(new InputStreamReader(fis2));
XMLUnit.setIgnoreWhitespace(true);
List<String> differences = compareXML(source, target);
try {
printDifferences(differences);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
public static void buildxml(String st, int totalDifferences)
{
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element root = document.createElement("Errorlist");
document.appendChild(root);
Element number = document.createElement("error");
root.appendChild(number);
Attr attr = document.createAttribute("i");
attr.setValue(st);
number.setAttributeNode(attr);
// create the xml file
//transform the DOM Object to an XML File
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource, streamResult);
System.out.println("Done creating XML File");
}
public static List<String> compareXML(Reader source, Reader target) throws
SAXException, IOException
{
Diff xmlDiff = new Diff(source, target);
DetailedDiff detailXmlDiff = new DetailedDiff(xmlDiff);
return detailXmlDiff.getAllDifferences();
}
public static void printDifferences(List<String> differences) throws IOException, ParserConfigurationException, TransformerException
{
int totalDifferences = differences.size();
System.out.println("===============================");
System.out.println("Total differences : " + totalDifferences);
System.out.println("================================");
for (Iterator<String> iterator = differences.iterator(); iterator.hasNext();) {
Object s=(Object)iterator.next();
String st=s.toString();
System.out.println(st);
buildxml(st,totalDifferences);
}