繁体   English   中英

LINQ where子句返回null

[英]LINQ where clause returns null

我正在尝试使用LINQ从xml获取值。 当我添加where子句时,我得到null。 当我删除where子句时,我从xml获得项目,但是'Value'没有属性。

这是我要从中获取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);
}

要获取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;

有关更多信息, XElement实现XNode XNode是基类,可枚举的Node可以包含除注释(XComment)之类的元素以外的其他内容,并且没有名称。 如果使用Elements属性,则将仅返回XElement对象。 XElement类包含与元素有关的数据,例如元素名称

暂无
暂无

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

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