2012-06-14 125 views
0

我想找到Xelement attribute.value,其中的子項具有一個具體的attribute.value。無法將類型'IEnumerable <XElement>'隱式轉換爲'bool'

string fatherName = xmlNX.Descendants("Assembly") 
          .Where(child => child.Descendants("Component") 
           .Where(name => name.Attribute("name").Value==item)) 
          .Select(el => (string)el.Attribute("name").Value); 

如何獲取attribute.value?它說什麼是一個布爾?

EDITED 本來我有下面的XML:

<Assembly name="1"> 
    <Assembly name="44" /> 
    <Assembly name="3"> 
    <Component name="2" /> 
    </Assembly> 
    </Assembly> 

我需要在那裏它的孩子(的XElement)具有attribute.value 的expecific在這個例子中attribute.value,我會得到字符串「3」,因爲我正在搜索子的父屬性attribute.value ==「2」

回答

2

由於嵌套的Where子句是如何寫入的。

內子句讀取

child.Descendants("Component").Where(name => name.Attribute("name").Value==item) 

這個表達IEnumerable<XElement>類型的結果,所以外子句讀取

.Where(child => /* an IEnumerable<XElement> */) 

然而Where預計Func<XElement, bool>類型的參數,在這裏,你最終通過在Func<XElement, IEnumerable<XElement>> - 因此錯誤。

我不提供更正的版本,因爲您的意圖根本不清楚給定的代碼,請相應地更新問題。

更新:

看起來像你想是這樣的:

xmlNX.Descendants("Assembly") 
    // filter assemblies down to those that have a matching component 
    .Where(asm => asm.Children("Component") 
        .Any(c => c.name.Attribute("name").Value==item)) 
    // select each matching assembly's name 
    .Select(asm => (string)asm.Attribute("name").Value) 
    // and get the first result, or null if the search was unsuccessful 
    .FirstOrDefault(); 
+0

,我剪輯我的問題。謝謝 – kmxillo

+0

@kmxillo:更新了答案。 – Jon

1

我想你想

string fatherName = xmlNX.Descendants("Assembly") 
          .Where(child => child.Elements("Component").Any(c => (string)c.Attribute("name") == item)) 
          .Select(el => (string)el.Attribute("name")).FirstOrDefault(); 
+0

謝謝爲我工作 – kmxillo

相關問題