简体   繁体   中英

Compare two xml files and highlight the differences

I could use some help with something i need to solve. I have two xml files and they are almost identical, i need to find what was changed, which means, i need to compare them line by line, and i need to highlight the changes in Visual Studio using c#

I've seen the tools but i would like to know if i can do it using code. I'm new to this so i could use a little guide.

My xml files are something like:

    <?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee ID="1" Name="JayT" JoinDate="3/1/2009">
    <Projects>
      <Project ID="1" Name="Project1" StartDate="2/1/2009" EndDate="4/1/2009" />
      <Project ID="2" Name="Project2" StartDate="3/5/2009" EndDate="4/1/2010" />
    </Projects>
  </Employee>
  <Employee ID="2" Name="Kim" JoinDate="4/1/2009">
    <Projects>
      <Project ID="3" Name="Project3" StartDate="5/1/2009" EndDate="10/1/2009" />
      <Project ID="2" Name="Project2" StartDate="3/5/2009" EndDate="4/1/2010" />
      <Project ID="6" Name="Project6" StartDate="3/5/2009" EndDate="4/1/2010" />
    </Projects>
  </Employee>
  <Employee ID="3" Name="Tom" JoinDate="6/1/2009">
    <Projects>
    </Projects>
  </Employee>
</Employees> 

File2 Data: Modified File (Referred to as "B XML" in the document) 

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee ID="1" Name="JayT" JoinDate="3/1/2009">
    <Projects>
      <Project ID="6" Name="Project6" StartDate="5/1/2009" EndDate="11/1/2009" />
    </Projects>   
  </Employee>
  <Employee ID="3" Name="Tom" JoinDate="6/1/2009">
    <Projects>
      <Project ID="5" Name="Project5" StartDate="7/1/2009" EndDate="12/1/2009" />
    </Projects>   
  </Employee> 
</Employees>

For example the code above, i need to highlight the changes, the rows added or removed

You can use XMLDocument class to load both the files and then compare each node's value and attributes using string comparison and possibly save the changes in a third xmldocument. http://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM