Vivek Shukla
Vivek Shukla

Reputation: 733

IEnumerable<XElement> compare is not same

I read an XML file by following two techniques.

  1. By reading the entire XML using Parse XElement XElement.Parse(File.ReadAllText(xmlfile)) Note: I know I shouldn't have used this technique.
  2. By using Load of XDocument XDocument.Load(xmlfile);

Then I tried creating a list of XElement by the following code snippet. To me, results look same but when I try to compare the two IEnumerable object, they aren't same.

What I am overlooking. Here is the code snippet

            // Read the xml db file.
            XElement xEle = XElement.Parse(File.ReadAllText(xmlfile));
            XDocument xDoc = XDocument.Load(xmlfile);


            List<XElement> xElementCollection = xEle.Elements("Map").ToList();
            List<XElement> xDocumentCollection = xDoc.Descendants("Map").ToList();

            bool bCompare = xElementCollection.Equals(xDocumentCollection);

bCompare results to false, however when I look at the data to both the lists. They look same.

Upvotes: 2

Views: 494

Answers (1)

hoodaticus
hoodaticus

Reputation: 3880

You basically need to go through each element in both lists and compare them to each other by value using the XNode.DeepEquals method.

if (xElementCollection.Count != xDocumentCollection.Count)
{
  bCompare = false;
}
else
{
   bCompare = true;
   for (int x = 0, y = 0; 
     x < xElementCollection.Count && y < xDocumentCollection.Count; x++, y++)
   {
     if (!XNode.DeepEquals(xElementCollection[x], xDocumentCollection[y]))
       bCompare = false;
   }
}

Upvotes: 1

Related Questions