title: XML compare Elements and Values using LINQ to XML
body: <pre><code>    XElement client = new XElement("Root",
          new XElement("Child2", "2"),
          new XElement("Child1", "1"),
          new XElement("Child3", "hello world"),
          new XElement("Child5", "5")
          );
  
      XElement server = new XElement("Root",
          new XElement("Child1", "1"),
          new XElement("Child2", "2"),
          new XElement("Child3", "3"),
          new XElement("Child4", "4")
      );
  </code></pre>
  
  <p>What would be the right LINQ to XML to compare these 2 XMLs and get that 
  the client has:<br>
    a) Element Child4 missing<br>
    b) Element Child5 is present but missing on the server<br>
    c) Element Child3 has different Value compare to the server one  </p>
  
  <p>Is there a simple way to get that those 3 "delta" nodes using LINQ to XML ??</p>
  
  <p>====================================<br>
  What did I try so far:<br>
  1) XmlDiff  </p>
  
  <pre><code>        var clientNode = XElement.Parse(client.ToString()).CreateReader();
          var serverNode = XElement.Parse(server.ToString()).CreateReader();
          var resultNode = new XDocument();
          var writer = resultNode.CreateWriter();
  
          var diff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreDtd | XmlDiffOptions.IgnorePrefixes | XmlDiffOptions.IgnoreXmlDecl);
          diff.Compare(clientNode, serverNode, writer);
          writer.Flush();
          writer.Close();
          resultNode.ToString();
  </code></pre>
  
  <p>...but it gives me some complex XML that I would have to decode.</p>
  
  <p>2) Converting it to string and comparing it</p>
  
  <pre><code>        string c = client.ToString().Trim();
          string s = server.ToString().Trim();
          c = c.Replace("Root", "").Replace("&lt;/", "").Replace("&lt;", "").Replace("&gt;", "");
          s = s.Replace("Root", "").Replace("&lt;/", "").Replace("&lt;", "").Replace("&gt;", "");
  
          List&lt;string&gt; c1 = c.Split(new[] { "\r\n" }, StringSplitOptions.None).ToList&lt;string&gt;();
          List&lt;string&gt; s1 = s.Split(new[] { "\r\n" }, StringSplitOptions.None).ToList&lt;string&gt;();
  
          List&lt;string&gt; delta1 = s1.Except(c1).ToList();
          List&lt;string&gt; delta2 = c1.Except(s1).ToList();
  </code></pre>
  
  <p>...but it gives me unreadable text back.</p>
  
  <p>============================================<br>
  So my hope is that with LINQ to XML, we can quickly just get a list of the delta elements, maybe with a tag stating in what XML the returning element "x" was located.</p>