LINQ to XML Newbie Question: Node Return Values ​​and Divisible Values

Hello!

I have XML like this:

<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>

      

I am currently doing the following to get the ID of each of the options:

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

      

I would also like to get the values ​​in the Title and Body child nodes of each Choice. How can i do this? Thank.

+1


source to share


2 answers


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

      



+1


source


Also XElement provides a bunch of type overloads, so you do things like ...



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

      

0


source







All Articles