c# - 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);
}
解决方案
要获取 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
implements XNode
。 XNode
是基类,Nodes 可枚举可以包含除元素以外的其他内容,例如注释 (XComment),并且没有名称。如果您使用该Elements
属性,您将只返回XElement
对象。XElement 类包含与元素相关的数据,例如元素名称
推荐阅读
- jenkins - 全局共享库自定义步骤 RejectedAccessException
- javascript - Solc 超过 Object.$db 的最大调用堆栈大小 [as dynCall_viiiiii]
- android - 根据 TextView 的内容高度设置 TextView 的 Padding
- sql - 使用 postgresql 连接一对多表时如何使用 LIMIT 和 OFFSET?
- python - 从 Python3.6 升级到 3.8 后 Pip、NumPy 和 Pytorch 消失了
- list - 有序列表的最小存储空间
- r - 错误:`position_jitterdodge()` 需要至少一种审美才能躲避
- android - Android Coroutines - 我如何等待两个不同的改造调用并将两个结果包装到一个 observable 中?
- apache-spark - Spark窗口函数并在每个分区的每列中获取第一个和最后一个值(窗口聚合)
- linkedin - LinkedIn API - 从广告帐户访问帐单交易/收据