2012-06-13 31 views
0

我正在開發自定義搜索控件並根據下面的示例XML設置其配置。因此,如果用戶使用了我的控制在自己的ASPX頁面,並在他的頁面聲明屬性爲:需要LINQ爲此XML結構選擇查詢的想法

<ccl:Search control id='searchtextbox' PageName='Master' /> 

然後我需要考慮頁面名稱名稱=「大師」,並設置在此提到的所有屬性。同樣,對於頁面名稱= 'SearchResult所'

<configuration> 
<Pagename name='Master'> 
    <Key id='DefaultText'>Search</Key> 
    <Key id='SearchBoxCss'>btn</Key> 
    <Key id='ButtonText'>Search</Key> 
    <Key id='AutocompleteEnabled'>true</Key> 
    <Key id='EnableFilterDropNames'>false</Key> 
    <Key id='FilterDropNames'>All Areas;Articles</Key>  
</Pagename> 
<Pagename name='SearchResults'> 
    <Key id='DefaultText'>Search</Key> 
    <Key id='SearchBoxCss'>btn</Key> 
    <Key id='ButtonText'>Search</Key> 
    <Key id='AutocompleteEnabled'>false</Key> 
    <Key id='EnableFilterDropNames'>false</Key> 
    <Key id='FilterDropNames'>All Areas;Articles;Products</Key>        
</Pagename> 
</configuration> 

你可以請建議必要LINQ代碼來選擇基於SearchResult所

我曾嘗試:

var ch = from elem in doc.Descendants("Pagename") 
        where elem.Attribute(XName.Get("name")).Value == "Master" 
        select new 
        { 
         Children = elem.Descendants("Key").Attributes() 
        }; 

這隻返回屬性列表而不是必需的值。

+0

您可以使用XPath這一點。看看這個:http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C – Rumplin

+0

這將是我的最後一個選擇。但目前正在尋找Linq。 –

回答

2
var ch = doc.Descendants("PageName") 
      .Where(p => (string)p.Attribute("name") == "Master") 
      .Elements("Key") 
      .Select(k => new 
         { 
          Id = (string)k.Attribute("id"), 
          Value = k.Value 
         } 
      ); 
+0

謝謝Marcin。這工作完美。 –

1

你可以試試:

elem.Descendants("PageName"). 
      Where(element => element.Attribute("Name").Value == "Master").First(). 
      Descendants().Select(element => element.Value); 

含義 - >獲得名稱爲「大師」,比採取一切它的孩子們的價值觀的第一個孩子節點

+0

這不會工作 - 「主」是一個屬性,而不是一個元素。 – MarcinJuraszek

+0

它向我拋出錯誤「序列不包含任何元素」。 –

+0

@Sayed:看到你的回覆太晚了,你當然是對的,我編輯了答案 – Clueless