Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法使用LINQ选择元素_C#_Xml_Linq - Fatal编程技术网

C# 无法使用LINQ选择元素

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="

我试图使用LINQ选择节点,但我无法理解为什么这个简单的查询不起作用

我的xml如下所示:

<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;