Hudlommen Hudlommen - 1 year ago 74
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>

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

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
    .Select(node => new Person
        Name = node.Element("name").Value,
        Sex = node.Element("sex").Value,
        Age = int.Parse(node.Element("age").Value)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download