LINQ to XML新手问题:按节点名称返回节点

Bul*_*nes 0 c# xml linq-to-xml c#-3.0

问候!

如果我有这样的XML:

<Root>
    <AlphaSection>
    .
    .
    .
    </AlphaSection>

    <BetaSection>
        <Choices>
            <SetA>
                <Choice id="choice1">Choice One</Choice> 
                <Choice id="choice2">Choice Two</Choice>
            </SetA>
            <SetB>
                <Choice id="choice3">Choice Three</Choice> 
                <Choice id="choice4">Choice Four</Choice>
            </SetB>
        </Choices>
    </BetaSection>

    <GammaSection>
    .
    .
    .
    </GammaSection>
</Root>
Run Code Online (Sandbox Code Playgroud)

我想获得"BetaSection"中的所有Choice项目,无论它们属于哪个"Set".我尝试过以下方法:

var choiceList = from choices in myXDoc.Root.Element("BetaSection").Elements("Choices")
                 where (choices.Name == "Choice")
                 select new
                 {
                     Name = choices.Attribute("id").Value,
                     Data = choice.Value
                 };
Run Code Online (Sandbox Code Playgroud)

但无济于事.我该怎么做?

谢谢.

Jon*_*eet 6

你根本不需要where子句 - 你只需要将Elements调用更改为Descendants:

var choiceList = myXDoc.Root
                       .Element("BetaSection")
                       .Descendants("Choice")
                       .Select(element => new
                               {
                                  Name = element.Attribute("id").Value,
                                  Data = element.Value;
                               });
Run Code Online (Sandbox Code Playgroud)

(我已经将它从查询表达式转换为简单的点表示法,因为我认为查询表达式并没有真正帮助你.)