C# 无法使用LINQ选择元素
我试图使用LINQ选择节点,但我无法理解为什么这个简单的查询不起作用 我的xml如下所示:C# 无法使用LINQ选择元素,c#,xml,linq,C#,Xml,Linq,我试图使用LINQ选择节点,但我无法理解为什么这个简单的查询不起作用 我的xml如下所示: <config> <func_list current_app="GSCC" flag="0"> <func id="GSCC"> <BLOCKS> <BLOCK id="1" type="ACTIONS"> <ITEMS> <ITEM id="
<config>
<func_list current_app="GSCC" flag="0">
<func id="GSCC">
<BLOCKS>
<BLOCK id="1" type="ACTIONS">
<ITEMS>
<ITEM id="1" type="UINT32" size="1" value="1" />
<ITEM id="2" type="UINT32" size="1" value="5" />
<ITEM id="3" type="UINT32" size="1" value="0" />
</ITEMS>
</BLOCK>
</BLOCKS>
</func>
</func_list>
</config>
现在,我有一个XElement(_funcNode),它指向“func”节点:
IEnumerable<XElement> xBlocks = from el in _funcNode.Descendants("BLOCK")
where el.Attribute("type").Value == "ACTIONS"
select el;
if (!xBlocks.Any()) return false;
IEnumerable xBlocks=来自_funcNode.substands(“块”)中的el
其中el.Attribute(“type”).Value==“ACTIONS”
选择el;
如果(!xBlocks.Any())返回false;
此外,xBlocks.Any()还会引发System.NullReferenceException异常。
有什么想法吗?您的主要问题是您的查询与xml不符
IEnumerable<XElement> xBlocks = from el in _funcNode.Descendants("BLOCK")
试着这样做
var doc = _funcNode.Descendants("BLOCK")
查看文档的外观。我解决了将查询更改为:
IEnumerable<XElement> xBlocks = from el in _funcNode.Descendants("BLOCK")
where (string)el.Attribute("type") == "ACTIONS"
select el;
IEnumerable xBlocks=来自_funcNode.substands(“块”)中的el
其中(字符串)el.Attribute(“type”)=“ACTIONS”
选择el;
问候。Select永远不会返回
null
。如果你得到一个NRE,那么你没有使用你展示的代码。这可能会给你一个错误el.Attribute(“type”)。Value
你的例子很好:我真的不知道为什么使用cast工作。我认为NRE是由WHERE子句引起的,正如@csharpwinphonexaml所说的。。但是为什么呢?可能是因为您的XML中有一个BLOCK
元素没有type
属性?\u funcNode.subjections()。元素(…)
将不会编译。也许你指的是元素
?我指的是,但我删除了它
IEnumerable<XElement> xBlocks = from el in _funcNode.Descendants("BLOCK")
where (string)el.Attribute("type") == "ACTIONS"
select el;