How to load XML to List<string>

Asked by At

I'm trying to use the contents of an XML file as the data source to a List

My XML

<History>
  <Articles>
    <Article></Article>
  </Articles>
  <Names>
    <Name>One</Name>
    <Name>Two</Name>
    <Name>three</Name>
    <Name>four</Name>
  </Names>
</History>

I have next code:

using (FileStream fs = new FileStream(this.fileName, FileMode.Open, FileAccess.Read))
{
    XDocument doc = XDocument.Load(fs);
    listName = doc.Descendants("Names").Select(x => x.Value).ToList();
}

but I got collection with single element - "OneTwothreefour"

How I can do it ? Thanks

1 Answers

2
Marco Salerno On Best Solutions

This is how to do it:

XDocument doc = XDocument.Load(filePath);
List<string> names = doc.Descendants("Name").Select(x => x.Value).ToList();