【问题标题】:IEnumerable<XElement> compare is not sameIEnumerable<XElement> 比较不一样
【发布时间】:2017-02-01 19:48:48
【问题描述】:

我通过以下两种技术读取 XML 文件。

  1. 通过使用 Parse XElement XElement.Parse(File.ReadAllText(xmlfile)) 读取整个 XML 注意:我知道我不应该使用这种技术。
  2. 通过使用 XDocument 的加载 XDocument.Load(xmlfile);

然后我尝试通过以下代码 sn-p 创建一个 XElement 列表。对我来说,结果看起来相同,但是当我尝试比较两个 IEnumerable 对象时,它们并不相同。

我忽略了什么。这是代码sn-p

            // 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 结果为 false,但是当我查看两个列表的数据时。它们看起来一样。

【问题讨论】:

  • Equals 将进行参考比较。您需要能够实际比较两个列表的内容。
  • @juharr - 是什么让所有这些评论答案诱使我认为一个问题没有得到回答???
  • @hoodaticus 但没有得到答复。会进行比较的“东西”是什么?评论提供线索但不提供答案。
  • xElementCollection 只查看根的子元素,而 xDocumentCollection 正在查看所有后代。

标签: c# xml c#-4.0 linq-to-xml


【解决方案1】:

您基本上需要遍历两个列表中的每个元素,并使用 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;
   }
}

【讨论】:

  • 谢谢@hoodaticus
  • @Vivek_Shukla 很高兴
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多