方式一 :通过标签的属性进行描述和存储
<?xml version="1.0" encoding="utf-8" ?>
<SkillInfo>
<SkillList>
<Skill
SkillID="20002"
SkillEngName="Smash"
TriggerType ="1"
ImageFile="data/gfx/image/gui_icon_skill_000.dds"
AvailableRace="7">
</Skill>
</SkillList>
</SkillInfo>
方式二 :通过标签之间的值进行描述和存储
<?xml version="1.0" encoding="utf-8" ?>
<skills>
<skill>
<id>2</id>
<name >法倫</name>
<damage>288</damage>
</skill>
</skills>
XmlFileDto.cs
public class XmlFileDto
{
public string SkillID { get; set; }
public string SkillEngName { get; set; }
public string TriggerType { get; set; }
public string ImageFile { get; set; }
public string AvailableRace { get; set; }
}
public class ReadXmlFileCode
{
public void ReadXmlFileTools()
{
//在上面给出XmlFileDto
List<XmlFileDto> list = new List<XmlFileDto>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("XMLFile.xml");
//读取根节点
XmlNode root = xmlDoc.ChildNodes[1];
//保存根节点下的元素集合
XmlNode skillNodeList = root.ChildNodes[0];
XmlNodeList nodeList = skillNodeList.ChildNodes;
foreach (XmlNode node in nodeList)
{
XmlFileDto xmlObj = new XmlFileDto();
//获取属性值
XmlAttributeCollection attrCol = node.Attributes;
XmlAttribute attrSkillID = attrCol["SkillID"];
xmlObj.SkillID = attrSkillID.Value;
XmlAttribute attrSkillEngName = attrCol["SkillEngName"];
xmlObj.SkillEngName = attrSkillEngName.Value;
XmlAttribute attrTriggerType = attrCol["TriggerType"];
xmlObj.TriggerType = attrTriggerType.Value;
XmlAttribute attrImageFile = attrCol["ImageFile"];
xmlObj.ImageFile = attrImageFile.Value;
XmlAttribute AvailableRace = attrCol["AvailableRace"];
xmlObj.AvailableRace = AvailableRace.Value;
//获取Name元素值
XmlNode nameNode = node.ChildNodes[0];
//XmlNode eleName = nameNode["name"];
xmlObj.Name = nameNode.InnerText;
list.Add(xmlObj);
}
foreach (XmlFileDto s in list)
{
Console.WriteLine(s.SkillID + " : " + s.SkillEngName + " : " + s.TriggerType + " : " + s.ImageFile + " : " + s.AvailableRace + " : " + s.Name);
}
}
}
class Skill
{
public int ID { get; set; }
public string Name { get; set; }
public int Damage { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
//Skill.cs在上面给出
List<Skill> list = new List<Skill>();
//专门解析XML文档的工具类
XmlDocument xmlDocument = new XmlDocument();
//传入路径
xmlDocument.Load("Skills.xml");
//FirstChild会把<?xml version="1.0" encoding="utf-8" ?>当做第一个节点,如果ChildNodes[0]会使后面ChildNodes获取值为空
XmlNode root = xmlDocument.ChildNodes[1];
//保存根节点下的节点集合
XmlNodeList skillList = root.ChildNodes;
foreach (XmlNode skill in skillList)
{
Skill skillObj = new Skill();
XmlElement idEle = skill["id"];
skillObj.ID = Int32.Parse(idEle.InnerText);
XmlElement nameEle = skill["name"];
skillObj.Name = nameEle.InnerText;
XmlElement damageEle = skill["damage"];
skillObj.Damage = Int32.Parse(idEle.InnerText);
list.Add(skillObj);
}
foreach (Skill s in list)
{
Console.WriteLine(s.ID+" : "+s.Name+" : "+ s.Damage);
}
}
}