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

2020-05-01 09:26发布

问题:

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?

回答1:

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



回答2:

Here is a simple example of an XML import. After this code executes, results will reflect if people were found (true or false), and msg will be a list of error messages (or empty if success).

            var results = true;
        var msg = new List<string>(0);
        XDocument aDocument = null;
        try
        {
            aDocument = XDocument.Load("");
        }
        catch (Exception e)
        {
            results = false;
            msg.Add(string.Format("Unable to open file:{0}", ""));
            msg.Add(e.Message);
        }

        if (aDocument != null)
        {
            var thePeople = aDocument.Descendants("Person").ToArray();

            if (thePeople.Any())
            {
                // there were people in the file. People is an array of XML Nodes containing your person.
                foreach (var pers in thePeople.Select(p => new Person().FromXML(p)))
                {
                    // here is a person
                }
            }
            else
            {
                results = false;
                msg.Add("No people found.");
            }

        }

Hope this helps.

Addition.

You could do something like this in your Person Class. I've added code to the original to illustrate usage.

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

    public XElement ToXML()
{

    return new XElement("Person", "Name", Name,
               new XElement("Age", Age),
               new XElement("Sex", Sex));
}

    public Person FromXML(XElement node)
    {
        try { Name = node.Element("Name").Value; }
        catch { Name = "Not Found"; }
        try { Age = Convert.ToInt16(node.Element("Age").Value); }
        catch { Age = -1; }
        try { Sex = node.Element("Sex").Value; }
        catch { Sex = ""; }
        return this;
    }
}


标签: c# xml linq uwp