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

前端 未结 2 1079
陌清茗
陌清茗 2021-01-28 09:31

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

2条回答
  •  不要未来只要你来
    2021-01-28 10:04

    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

提交回复
热议问题