首页 > 解决方案 > LINQ where 子句返回 null

问题描述

我正在尝试使用 LINQ 从 xml 获取值。当我添加 where 子句时,我得到空值。当我删除 where 子句时,我从 xml 中获取项目,但没有“值”的属性。

这是我试图从中获取 BatchId、ResultCode 和 SearchId 值的 xml。

{<WsSearchReply xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ExtensionData />
  <BatchId>6787350</BatchId>
  <Hits />
  <ResultCode>NO_HITS</ResultCode>
  <SearchId>67292500</SearchId>
</WsSearchReply>}

This returns 4 items:
IEnumerable<XNode> dps = from el in d.Root.Nodes()
                              select el;

this doesn't return any records:
IEnumerable<XNode> dps = from el in d.Root.Nodes()
                         where el.Equals("<ExtensionData />")
                         select el;

using System.Xml;
using System.Xml.Linq;

string text = Serializer.SerializeObject<CchSearchService.WsSearchReply>(reply, true);

XDocument d = new XDocument();
XElement e = XElement.Parse(text);
d.Add(e);

IEnumerable<XNode> dps = from el in d.Root.Nodes()
//where el.Equals("<ExtensionData />")
 select el;

foreach (XNode el in dps)
{
    string x = el.ToString();
    Console.WriteLine(el);
}

标签: c#linq

解决方案


要获取 ExtensionData 元素,您可以简单地使用以下内容:

IEnumerable<XElement> dps = d.Root.Elements("ExtensionData");

这本质上是一种快速的方法(您建议您必须在评论中为此使用 lync,下面的代码是不必要的)

IEnumerable<XElement> dps = from el in d.Root.Elements() where el.Name.LocalName.Equals("ExtensionData") select el;

有关更多信息,请使用XElementimplements XNodeXNode是基类,Nodes 可枚举可以包含除元素以外的其他内容,例如注释 (XComment),并且没有名称。如果您使用该Elements属性,您将只返回XElement对象。XElement 类包含与元素相关的数据,例如元素名称


推荐阅读