2014-09-24 73 views
-2

我想选择使用LINQ节点,但我不明白为什么这个简单的查询不起作用。无法选择与LINQ的XElements

我的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)指向 '功能' 节点:

IEnumerable<XElement> xBlocks = from el in _funcNode.Descendants("BLOCK") 
           where el.Attribute("type").Value == "ACTIONS" 
           select el; 

if (!xBlocks.Any()) return false; 

另外,xBlocks.Any()抛出System.NullReferenceException异常。 有什么想法?

+3

选择永远不会返回'null'。如果你得到一个NRE,那么你没有使用你展示的代码。 – Servy 2014-09-24 15:19:33

+0

这可能会给你一个错误'el.Attribute(“type”)。Value' – csharpwinphonexaml 2014-09-24 15:22:46

+0

你的例子工作正常:https://dotnetfiddle.net/vOmeXz – 2014-09-24 15:26:46

回答

0

我解决了更改查询到:

IEnumerable<XElement> xBlocks = from el in _funcNode.Descendants("BLOCK") 
           where (string)el.Attribute("type") == "ACTIONS" 
           select el; 

问候。

0

你最主要的问题是你的查询没有加到你的xml中。

IEnumerable<XElement> xBlocks = from el in _funcNode.Descendants("BLOCK") 

要使用什么是

_funcNode.Descendants().Elements("BLOCK") 

尝试这样做

var doc = _funcNode.Descendants("BLOCK") 

看什么文档的样子。

+0

'_funcNode.Descendants()。Element(...)'不会编译。也许你的意思是'Elements'? – 2014-09-24 15:27:40

+0

我会说......因为我放弃了一个“s”,所以你下降了... – DidIReallyWriteThat 2014-09-24 15:31:55

+0

我做过了,但我删除了它 – 2014-09-24 15:32:25