对XMl文件的操作

 

一.在工程目录下,新建txt文件取名Skills,修改其属性运行时复制到工作目录中;

右键选择Open with

选择Xml方便编辑txt内容

 

二.新建一个SkillInfo类,用来存储Skill信息

class SkillInfo
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Damage { set; get; }
    public string Language { get; set; }
    public override string ToString()
    {
        return string.Format("ID:" + ID + ",Name:" + Name + ",Damage:" + Damage + ",Language:" + Language);
    }
}

 

static void Main(string[] args)
        {
            List<SkillInfo> SkillList = new List<SkillInfo>();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("Skills.txt");
            XmlNode skills = xmlDoc.FirstChild;
            XmlNodeList skillList = skills.ChildNodes;
            foreach (XmlNode skill in skillList)
            {
                XmlNodeList skillInfo = skill.ChildNodes;
                SkillInfo skillObject = new SkillInfo();
                foreach (XmlNode info in skillInfo)
                {
                    if (info.Name== "ID")
                    {
                        skillObject.ID =int.Parse(info.InnerText);
                    }
                    if (info.Name == "Name")
                    {
                        skillObject.Name = info.InnerText;
                        skillObject.Language = info.Attributes[0].Value;
                    }
                    if (info.Name == "Damage")
                    {
                        skillObject.Damage = int.Parse(info.InnerText);
                    }
                }
                SkillList.Add(skillObject);
            }
            foreach(SkillInfo list in SkillList)
            {
                Console.WriteLine(list.ToString());
            }
            Console.ReadKey();
        }


Skills.txt文本编写格式如下:

 

结果如下:

Unity中将一个对象写入XML文件中的操作如下:

  string xmlPath = Application.dataPath + "/AssetbundleConfig.xml";
        if (File.Exists(xmlPath)) File.Delete(xmlPath);
        FileStream fileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
        StreamWriter sw = new StreamWriter(fileStream, System.Text.Encoding.UTF8);
        XmlSerializer xs = new XmlSerializer(config.GetType());
        xs.Serialize(sw, config);
        sw.Close();
        fileStream.Close();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值