如何将XML格式的数据添加到列表中?我试着从一个xml文件中读取,但它很笨拙,而且我得到的很多数据都来自一个孩子。我把姓名、年龄等合而为一,所以无法将其添加到列表中。我的xml文件如下所示:30BoyMale28GirlFemale在我的xaml.cs文件中我有:Lista=newList();varlocalFolder=ApplicationData.Current.LocalFolder;XML文档XML文档;varfile=awaitlocalFolder.TryGetItemAsync("FoodData.xml")asIStorageFile;xmlDocument=awaitXmlDocument.LoadFromFileAsync(文件);有了这个,我需要做一个设置,我可以从XML中获取数据并将其放入这样的列表中:add(listTest{Name="*来自XML的数据*",Age="*来自XML的数据*",Sex="*来自XML的数据*"});我试过使用LINQ并使用p.NodeName=="xxx"进行搜索,但我似乎没有得到任何数据。有人能告诉我如何从我的xml中获取数据到列表中吗?假设你有这个类:publicclassPerson{publicstringName{get;放;}publicstringSex{得到;放;}publicintAge{得到;放;然后,要加载XML文件,您可以执行以下操作:vardoc=XDocument.Load("pathtoyourfile");varpeople=doc.Root.Descendants("person").Select(node=>newPerson{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将是错误消息列表(如果成功则为空)。变量结果=真;varmsg=new列表(0);XDocumentaDocument=null;尝试{aDocument=XDocument.Load("");}catch(异常e){结果=false;msg.Add(string.Format("无法打开文件:{0}",""));msg.Add(e.Message);}if(aDocument!=null){varthePeople=aDocument.Descendants("Person").ToArray();if(thePeople.Any()){//文件中有人。People是一个包含你的人的XML节点数组。foreach(varpersinthePeople.Select(p=>newPerson().FromXML(p))){//这里是一个人}}else{results=false;消息。Add("没有找到人。");}}希望这可以帮助。添加。您可以在Person类中做类似的事情。我已将代码添加到原始代码中以说明用法。以上就是C#学习教程:如何将XML格式的数据添加到列表中?所有分享的内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——publicclassPerson{publicstringName{get;放;}publicintAge{得到;放;}publicstringSex{得到;放;}publicXElementToXML(){returnnewXElement("Person","Name",Name,newXElement("Age",Age),newXElement("Sex",Sex));}publicPersonFromXML(XElementnode){try{Name=node.Element("Name").Value;}catch{名称=“未找到”;}try{Age=Convert.ToInt16(node.Element("Age").Value);}赶上{年龄=-1;}尝试{Sex=node.Element("Sex").Value;}catch{性别="";}返回这个;}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
