LINQ搜索不同级别的属性

时间:2013-03-20 14:20:42

标签: c# linq linq-to-xml

我想用LINQ技术搜索xml文件,但有一些困难。 我想找到所有具有属性值和一些搜索条件的孩子

我的XML(结构化数据)如下所示:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<LanguageMenu>
    <Menu language="English" name ="Menu" numOfMenus="1">
        <MainItem ID="e_mnuMain1" name="File" level="0"></MainItem>
        <MainItem ID="e_mnuMain2" name="Edit" level="0"></MainItem>
        <MainItem ID="e_mnuMain3" name="Query" level="0"></MainItem>
        <MainItem ID="e_mnuMain4" name="Traffic" numOfSubItem="4" level="0"> 
            <SECOND name="Vendors" value="FIN3010" level="1" father="3"></SECOND>
            <SECOND name="Buyers" value="FIN3020" level="1" father="3" ></SECOND>
            <SECOND name="General ledger" value="FIN3030" level="1" father="3"></SECOND>
            <SECOND name="Accounts" value="FIN3040" level="1" father="3">
                <THIRD name="Home Accounts" value="FIN3010" level="2" father="5" grantfather="3"/>
                <THIRD name="Foreign accounts" value="FIN3050" level="2" father="5" grantfather="3"/>
            </SECOND>
        </MainItem>
    </Menu>
</LanguageMenu>

使用LINQ我想实现找到所有以Element MainItem开头且值为FIN3010的子项。 根据我的XML,它应该返回供应商和家庭帐户。

我也想得到那个childer的父母,所以我想要实现的输出将是这样的:

Traffic - Vendors
Traffic - Accounts - Home Accounts

我坚持使用这段代码:

XElement xelement = XElement.Load("../../xmlFile");
var x = from a in xelement.Descendants("SECONDS")
        where a.Attribute("value") != null 
        && (string)a.Attribute("value").Value.ToUpper() == txtSifra.Text.ToUpper()
        select a;
foreach (XElement xEle in x)
{
    //TODO
}

1 个答案:

答案 0 :(得分:0)

这个怎么样:

var x = from a in xelement.Descendants("MainItem")
                          .Descendants()
        where a.Attribute("value") != null && 
              a.Attribute("value").Value
                                  .Equals(txtSifra.Text, 
                                          StringComparison.InvariantCultureIgnoreCase)
        select a;
foreach (XElement xEle in x)
{
        // items will contain all nodes (inclusive) between MainItem and xEle
        var items = xEle.AncestorsAndSelf()
                        .Where(x1 => x1.AncestorsAndSelf("MainItem")
                                       .Any())
                        .OrderBy(x1 => x1.Ancestors().Count());
        var names = items.Attributes("name").Select(a => a.Value).ToArray();
        Console.WriteLine(string.Join(" - ", names));
}

这个输出是:

Traffic - Vendors
Traffic - Accounts - Home Accounts