Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to diff-compare two xml files using java

Tags:

java

diff

xml

I have two xml files that I want to compare:

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>

I want to compare the two files and return which records were added, deleted, or updated. old.xml contains 2 <employee> records and new.xml contains 3 <employee> records.

I'd like the results to be like this:

Added records 2 : ex:- employee.id=106 and employee.id=107

Deleted records 1 : ex:- employee.id=102

Updated records 1: ex:- employee.id=105 updated with ----

What is the best way to diff these two XML files to get these results?

like image 958
m Goodman Avatar asked Feb 17 '26 08:02

m Goodman


2 Answers

This sounds similar to Best way to compare 2 XML documents in Java. I'd suggest checking out XMLUnit:

http://xmlunit.sourceforge.net/

like image 123
Marc Baumbach Avatar answered Feb 19 '26 22:02

Marc Baumbach


What I would do

@XmlRootElement
class Employees {
    List<Employee> list;
}

class Employee {
    int id;
    String name;
    String department;
}

Unmarshal xmls. Create 2 maps and do following

    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
    }
like image 21
Evgeniy Dorofeev Avatar answered Feb 19 '26 23:02

Evgeniy Dorofeev