1 <skills> 2 <skill> 3 <id>2</id> 4 <name lang="cn">天下无双</name> 5 <damage>123</damage> 6 </skill> 7 <skill> 8 <id>3</id> 9 <name lang="cn">永恒零度</name> 10 <damage>90</damage> 11 </skill> 12 <skill> 13 <id>4</id> 14 <name lang="en">omg</name> 15 <damage>400</damage> 16 </skill> 17 </skills>
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace XMLConsoleApp 6 { 7 /// <summary> 8 /// 技能类-对应XML SkillInfo.txt 9 /// </summary> 10 public class Skill 11 { 12 public int Id { get; set; } 13 14 public string Name { get; set; } 15 16 public string Lang { get; set; } 17 18 public int Damage { get; set; } 19 20 public override string ToString() 21 { 22 return string.Format("Id:{0},Name:{1},Lang:{2},Damage:{3}",Id,Name,Lang,Damage); 23 } 24 25 } 26 }
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Text; 5 using System.Xml; 6 7 namespace XMLConsoleApp 8 { 9 /// <summary> 10 /// 读取XML文档 11 /// </summary> 12 public class ReadXMLDocumentHelper 13 { 14 15 16 /// <summary> 17 /// 读取XML文档信息,转换为集合 18 /// </summary> 19 public static void ReadXML() 20 { 21 //实例化技能对象集合 22 List<Skill> skillList = new List<Skill>(); 23 24 //实例化XmlDocument 用于解析XML文档 25 XmlDocument xmlDoc = new XmlDocument(); 26 27 //加载文件 28 //xmlDoc.Load("SkillInfo.txt"); 29 30 //方式二 加载XML字符串 31 xmlDoc.LoadXml(File.ReadAllText("SkillInfo.txt")); 32 33 //获取根节点(XmlNode代表结点) 34 XmlNode rootNode = xmlDoc.FirstChild; 35 36 //获取子节点集合 37 XmlNodeList skillNodeList = rootNode.ChildNodes; 38 39 40 foreach (XmlNode skillNode in skillNodeList) 41 { 42 XmlNodeList fieldNodeList = skillNode.ChildNodes; 43 44 Skill skill = new Skill(); 45 46 foreach (XmlNode fieldNode in fieldNodeList) 47 { 48 if (fieldNode.Name == "id") 49 { 50 int id = Int32.Parse(fieldNode.InnerText); 51 skill.Id = id; 52 } 53 else if (fieldNode.Name == "name") 54 { 55 string name = fieldNode.InnerText; 56 skill.Name = name; 57 skill.Lang = fieldNode.Attributes[0].Value; 58 } 59 else 60 { 61 skill.Damage = Int32.Parse(fieldNode.InnerText); 62 } 63 } 64 65 skillList.Add(skill); 66 } 67 68 foreach (Skill skillInfo in skillList) 69 { 70 Console.WriteLine(skillInfo); 71 } 72 73 } 74 } 75 }
原文:https://www.cnblogs.com/ABC-wangyuhan/p/14226062.html