Find the delta between two xelements using "except" C #

My first XElement:

XElement sourceFile = new XElement("source", from o in Version1.Element("folder").Elements("folders").ElementAt(0).Elements("folder") where o.Name != null && o.Name == "folder" select new XElement("data", new XElement("name",(string) o.Attribute("name")), new XElement("filesCount", (string)o.Attribute("folderCount")), new XElement("filesCount", (string)o.Attribute("filesCount")) )); //,o) 

My second:

 XElement targetFile = new XElement("target", from o in Version2.Element("folder").Elements("folders").ElementAt(0).Elements("folder") where o.Name != null && o.Name == "folder" select new XElement("data", new XElement("name", (string)o.Attribute("name")), new XElement("filesCount", (string)o.Attribute("folderCount")), new XElement("filesCount", (string)o.Attribute("filesCount")) )); 

I would like to find a delta (the source always contains the target) something like this ... sad, mine doesn't work:

 XElement nodenotinsource = new XElement ("result", from y in sourceFile.Elements().Except(from o in targetFile.Elements()) select new XElement("ttt", y.Element("name").Value)); 

Version1 and Version2 were created as follows:

 XElement Version1 = XElement.Load(@"C:\output\xmltestO.xml"); XElement Version2 = XElement.Load(@"C:\output\xmltestO.xml"); 

where both files are the same, except for the change that the program should find ...

0
comparison c # xml xelement
source share
1 answer

(In the code of your question, you upload the same file to Version1 and Version2 . I assume this is a typo and you are actually uploading different files.)

You cannot use Except to compare XElement s. You create separate instances of XElement . Although they contain the same content, they will not be compared as equal.

Therefore, you need to compare the source data. For example:

 var sourceData = from o in Version1.Element("folder").Elements("folders").ElementAt(0).Elements("folder") where o.Name != null && o.Name == "folder" select new { Name = (string) o.Attribute("name")), FolderCount = (string)o.Attribute("folderCount")), FilesCount = (string)o.Attribute("filesCount")) }; 

Then do the same with the target file to get targetData . Finally, you can compare them using Except , and then generate your final XElement :

 XElement nodenotinsource = new XElement ("result", from y in sourceData.Except(targetData) select new XElement("ttt", y.Name)); 
0
source share

All Articles