我有两个我要比较的xml文件:
old.xml:
<EMPLOYEES>
<employee>
<id>102</id>
<name>Fran</name>
<department> THIS IS COMPUTER DEPARTMENT </department>
</employee>
<employee>
<id>105</id>
<name>Matthew</name>
<department> THIS IS SCIENCE AND TECHNOLOGY </department>
</employee>
</EMPLOYEES>
new.xml:
<EMPLOYEES>
<employee>
<id>105</id>
<name>Matthew</name>
<department> THIS IS SCIENCE AND TECHNOLOGY **Modified *** </department>
</employee>
<employee>
<id>106</id>
<name>xyz</name>
<department> THIS IS SCIENCE AND TECHNOLOGY </department>
</employee>
<employee>
<id>107</id>
<name>Francis</name>
<department> THIS IS XYZ </department>
</employee>
</EMPLOYEES>
我想比较两个文件并返回添加,删除或更新的记录。 old.xml
包含2条<employee>
条记录,new.xml
包含3条<employee>
条记录。
我希望结果如下:
添加了记录 2:例如: - employee.id = 106和employee.id = 107
删除记录 1:例如: - employee.id = 102
更新记录 1:例如: - employee.id = 105用----更新
区分这两个XML文件以获得这些结果的最佳方法是什么?
答案 0 :(得分:2)
这听起来与Best way to compare 2 XML documents in Java类似。我建议查看XMLUnit:
答案 1 :(得分:0)
我会做什么
@XmlRootElement
class Employees {
List<Employee> list;
}
class Employee {
int id;
String name;
String department;
}
解组xml。创建2个地图并执行以下操作
Map<Integer, Employee> map1 = ...
Map<Integer, Employee> map2 = ...
// see Map.retainAll API
map1.keySet().retainAll(map2.keySet());
// now map1 contains common employees
for (Integer k : map1.keySet()) {
Employee e1 = map1.get(k);
Employee e2 = map2.get(k);
// compare name and department
}
答案 2 :(得分:0)
对于逻辑差异,即两个xml文件中相应节点之间的差异,您可以使用节点类的isEqualNode(节点节点)方法。
对于逐行比较,Scanner易于使用。示例代码 -
public void compareFiles (Scanner file1, Scanner file2) {
String lineA ;
String lineB ;
int x = 1;
while (file1.hasNextLine() && file2.hasNextLine()) {
lineA = file1.nextLine();
lineB = file2.nextLine();
if (!lineA.equals(lineB)) {
System.out.print("Diff " + x++ + "\r\n");
System.out.print("< " + lineA + "\r\n");
System.out.print("> " + lineB + "\r\n");
}
}
}