如何将XML中的数据添加到列表?

我尝试从一个xml文件中读取,但它非常clonky和我得到的很多数据来自一个孩子。 我在一个中得到了姓名,年龄等等,因此我无法将其添加到列表中。

我的xml文件如下所示:

  30 Boy Male   28 Girl Female  

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

  List a = new List(); var localFolder = ApplicationData.Current.LocalFolder; XmlDocument xmlDocument; var file = await localFolder.TryGetItemAsync("FoodData.xml") as IStorageFile; xmlDocument = await XmlDocument.LoadFromFileAsync(file); 

有了这个我需要进行设置,我可以从XML中获取数据并将其放入list如下所示:

 a.add(listTest {Name = "*DATA FROM XML*", Age ="*DATA FROM XML*", Sex="*DATA FROM XML*"}); 

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

有人可以告诉我如何从我的xml到列表中的数据?

我们假设你有这个课程:

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

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

 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导入示例。 执行此代码后,结果将反映是否找到了人(true或false), msg将是错误消息列表(如果成功则为空)。

  var results = true; var msg = new List(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."); } } 

希望这可以帮助。

加成。

您可以在Person Class中执行类似的操作。 我已经在原始代码中添加了代码来说明用法。

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