Home > Net >  How do I extract these XML elements into a List<string>?
How do I extract these XML elements into a List<string>?

Time:07-18

I have this XML in which I am trying to get the output values of the <Daily> element.

<Person>
<Man>
    <Routine> 
        <Entry>
            <Daily>food</Daily>
            <Daily>drink</Daily>
            <Daily>sleep</Daily>
            <Daily>driving</Daily>
            <Daily>work</Daily>
        </Entry>
    </Routine>
</Man>
</Person>

C# code:

verb = (from el in root.Elements("Entry").Descendants("Daily")
  select(string) el)
 .Aggregate(new StringBuilder(), (att, i) => att.Append(i), x => x.ToString());

Console.WriteLine(verb);

Through this C# code, I am able to get all the values in <Daily> individually be hovering over the el string while debugging. However, verb displays them all together like this, without any spaces.

"fooddrinksleepdrivingwork"

What changes should I make to my code to get the elements as a List<string> or, at least, a string separated by commas?

CodePudding user response:

you're concatenating the elements value in one string, instead of storing them into a List<string>. Calling ToList instead of Aggregate would do the trick.

verb = (from el in root.Elements("Entry").Descendants("Daily")
  select(string) el)
  .ToList();

you can also do this :

var daily = root
                .Descendants("Entry")
                .Elements("Daily")
                .Select(x => x.Value)
                .ToList();
  • Related