如何将 XML 中的数据添加到列表<>? [英] How do i add data from XML to list&lt;&gt;?

查看:28
本文介绍了如何将 XML 中的数据添加到列表<>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从 xml 文件中读取数据,但它非常笨拙,而且我获得的很多数据都是从孩子那里收集的.我将姓名、年龄等信息合二为一,因此无法将其添加到列表中.

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.

我的 xml 文件如下所示:

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>

在我的 xaml.cs 文件中,我有:

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);

然后,我需要进行设置,以便我可以从 XML 中获取数据并将其放入 list<> 中,如下所示:

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*"});

我尝试使用 LINQ 并使用 p.NodeName == "xxx" 进行搜索,但我似乎没有得到任何数据.

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

有人可以告诉我如何将数据从我的 xml 获取到列表吗?

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

推荐答案

假设你有这个类:

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

然后,要加载您的 XML 文件,您可以执行以下操作:

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();

请参阅 https://msdn.microsoft.com/en-us/library/bb353813.aspx

这篇关于如何将 XML 中的数据添加到列表<>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆