我需要比较两个 XML 文件并在另一个 xml 文件中打印结果此代码比较并正确打印控制台中的差异,但它仅在 XML 文件中打印一行。此外,当我在控制台中查看输出时,似乎它正在创建 n 个等于总差异的 xml 文件。任何帮助表示赞赏。在此先感谢。
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);
}