標籤:
簡單的xml操作--解析技能xml
xml檔案
<skills> <skill> <id>1</id> <name lang="cn">大荒囚天指</name> <demage>100</demage> </skill> <skill> <id>2</id> <name lang="en">絕對零度</name> <demage>200</demage> </skill> <skill> <id>3</id> <name lang="ger">青龍魂</name> <demage>1000</demage> </skill></skills>
建立對應的skill類,重寫了ToString方法 方便輸出
class Skill { public int ID { get; set; } public string Name { get; set; } public string Lang { get; set; } public int Demage { get; set; } public override string ToString() { return string.Format("Id:{0},Name:{1},Lang:{2},Demage:{3}", ID, Name, Lang, Demage); } }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Xml; 7 8 namespace xml操作 9 {10 class Program11 {12 static void Main(string[] args)13 {14 List<Skill> skillList = new List<Skill>();15 16 XmlDocument xmlDoc = new XmlDocument();17 xmlDoc.Load("skillInfo.txt");18 19 //根節點20 XmlNode root = xmlDoc.FirstChild;21 22 XmlNodeList skillsNodeList = root.ChildNodes;23 foreach (XmlNode skillNode in skillsNodeList)24 {25 Skill skill = new Skill();26 foreach (XmlNode filedNode in skillNode.ChildNodes)27 {28 if (filedNode.Name == "id")29 {30 skill.ID = int.Parse( filedNode.InnerText);31 }32 else if (filedNode.Name == "name")33 {34 skill.Name = filedNode.InnerText;35 skill.Lang = filedNode.Attributes[0].Value;36 }37 else if (filedNode.Name == "demage")38 {39 skill.Demage = int.Parse(filedNode.InnerText);40 }41 }42 skillList.Add(skill);43 }44 45 foreach (var item in skillList)46 {47 Console.WriteLine(item);48 }49 }50 }51 }
c#xml操作