3

我有两个要比较的 xml 文件:

旧的.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>

新的.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:ex:-employee.id=105 更新为 ----

区分这两个 XML 文件以获得这些结果的最佳方法是什么?

4

3 回答 3

2

这听起来类似于Best way to compare 2 XML documents in Java。我建议检查 XMLUnit:

http://xmlunit.sourceforge.net/

于 2013-01-10T22:14:34.707 回答
1

我会做什么

@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
    }
于 2013-01-11T02:53:28.960 回答
0

对于逻辑差异,即两个xml文件中对应节点的差异,可以使用节点类的isEqualNode(Node node)方法。

对于逐行比较,扫描仪易于使用。示例代码 -

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

            } 
于 2013-03-25T11:02:04.280 回答