Hudlommen Hudlommen - 1 month ago 7
C# Question

How do i add data from XML to list<>?

I try to read from an xml file, but its very clonky and a lot of the data I get is in bunch from a child. I get the Name, Age, and so on in one and therefor I can't add it to a list.

My xml-file looks like this:

<?xml version="1.0" encoding="UTF-8"?><People>
<Person>
<Age>30</Age>
<Name>Boy</Name>
<Sex>Male</Sex>
</Person>
<Person>
<Age>28</Age>
<Name>Girl</Name>
<Sex>Female</Sex>
</Person>




And in my xaml.cs file I have:

List<listTest> a = new List<listTest>();
var localFolder = ApplicationData.Current.LocalFolder;
XmlDocument xmlDocument;
var file = await localFolder.TryGetItemAsync("FoodData.xml") as IStorageFile;
xmlDocument = await XmlDocument.LoadFromFileAsync(file);


And with that I need to make a setup where I can take data from the XML and put it into
list<>
like this:

a.add(listTest {Name = "*DATA FROM XML*", Age ="*DATA FROM XML*", Sex="*DATA FROM XML*"});


I have tried to use LINQ and use
p.NodeName == "xxx"
to make searches, but I don't seem to get any data out.

Can some one show me how to get the data from my xml to a list?

Answer

Let's assume you have this class:

public class Person
{
    public string Name { get; set; }
    public string Sex { get; set; }
    public int Age { get; set; }
}

Then, to load your XML file, you could do something like:

var doc = XDocument.Load("path to your file");

var people = doc.Root
    .Descendants("person")
    .Select(node => new Person
    {
        Name = node.Element("name").Value,
        Sex = node.Element("sex").Value,
        Age = int.Parse(node.Element("age").Value)
    })
    .ToList();

See https://msdn.microsoft.com/en-us/library/bb353813.aspx

Comments