2014-09-24 23 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