需要对此 XML 结构的 LINQ 选择查询有一个想法

本文关键字:查询 选择 有一个 LINQ XML 结构 | 更新日期: 2023-09-27 18:36:56

我正在开发一个自定义搜索控件,并根据下面的示例 XML 设置其配置。因此,如果用户在其 ASPX 页中使用我的控件,并在其页中声明一个属性为:

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

那么我需要考虑页面名称='Master'并设置下面提到的所有属性。同样,对于页面名称='搜索结果'

<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 代码进行选择

我尝试过的:

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

这只返回属性列表,而不是必要的值。

需要对此 XML 结构的 LINQ 选择查询有一个想法

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

你可以试试:

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

含义 ->获取名为"Master"的第一个子节点,然后获取其所有子节点的值