简体   繁体   English

IEnumerable<XElement> 比较不一样

[英]IEnumerable<XElement> compare is not same

I read an XML file by following two techniques.我通过以下两种技术读取 XML 文件。

  1. By reading the entire XML using Parse XElement XElement.Parse(File.ReadAllText(xmlfile)) Note: I know I shouldn't have used this technique.通过使用 Parse XElement XElement.Parse(File.ReadAllText(xmlfile))读取整个 XML 注意:我知道我不应该使用这种技术。
  2. By using Load of XDocument XDocument.Load(xmlfile);通过使用 XDocument XDocument.Load(xmlfile); Load

Then I tried creating a list of XElement by the following code snippet.然后我尝试通过以下代码片段创建 XElement 列表。 To me, results look same but when I try to compare the two IEnumerable object, they aren't same.对我来说,结果看起来相同,但是当我尝试比较两个 IEnumerable 对象时,它们并不相同。

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. bCompare 结果为假,但是当我查看两个列表的数据时。 They look same.他们看起来一样。

You basically need to go through each element in both lists and compare them to each other by value using the XNode.DeepEquals method.您基本上需要遍历两个列表中的每个元素,并使用 XNode.DeepEquals 方法按值将它们相互比较。

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;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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