【问题标题】:LINQ to XML Newbie Question: Returning Nodes Values AND Decendant ValuesLINQ to XML 新手问题:返回节点值和后代值
【发布时间】:2008-12-04 00:58:09
【问题描述】:

您好!

我有一些这样的 XML:

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

    <BetaSection>
        <Choices>
            <SetA>
                <Choice id="choice1">
                    <Title>Choice 1 Title</Title>
                    <Body>Choice 1 Body</Body>
                </Choice> 
                <Choice id="choice2">
                    <Title>Choice 2 Title</Title>
                    <Body>Choice 2 Body</Body>                
                </Choice>
            </SetA>
            <SetB>
                <Choice id="choice3">
                    <Title>Choice 3 Title</Title>
                    <Body>Choice 3 Body</Body>
                </Choice> 
                <Choice id="choice4">
                    <Title>Choice 4 Title</Title>
                    <Body>Choice 4 Body</Body>                
                </Choice>
            </SetB>
        </Choices>
    </BetaSection>

    <GammaSection>
    .
    .
    .
    </GammaSection>
</Root>

我目前正在执行以下操作来检索每个选项的 ID:

var choiceList = myXDoc.Root
                       .Element("BetaSection")
                       .Descendants("Choice")
                       .Select(element => new
                               {
                                  ID = element.Attribute("id").Value,
                                  // Title = ?
                                  // Body = ?
                               });

我还想获取每个选项的 Title 和 Body 子节点中的值。我该怎么办?谢谢。

【问题讨论】:

    标签: c# xml c#-3.0 linq-to-xml


    【解决方案1】:
    element => new {
                    ID = element.Attribute("id").Value,
                    Title = element.Element("Title").Value,
                    Body = element.Element("Body").Value
                   });
    

    【讨论】:

      【解决方案2】:

      XElement 还提供了一系列类型转换重载,因此您可以执行...

      element => new {
                       ID = (string)element.Attribute("id"),
                       title = (string)element.Element("Title"),
                       Body = (string)element.Element("Body")
                     });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-11
        • 2012-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多