如何将XML中的数据添加到list<> ;? [英] How do i add data from XML to list<>?
问题描述
我尝试从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文件如下:
<?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?
推荐答案
让我们假设您拥有此类:
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; }
}
然后,要加载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中的数据添加到list<> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!