在程序有时候需要从文本中读取数据,或者把数据保存到文件中,使用XML文件来存储数据是一个不错的选择。下面介绍一下在Unity3D中使用C#如何进行XML文件的读写。
1、需要引入的包
- using UnityEngine;
- using System.Collections;
- using System.Xml;
2、编辑你的XML文件
- <?xml version="1.0" encoding="utf-8"?>
- <RoleRoot>
- <Role faction="0">
- <BaseAttribute grade="1" force="2" spirit="1" agility="1" endurance="1" wisdom="1"/>
- <FightAttribute hp="1" mp="1" generalHurt="1" generalDefense="1" skillHurt="1"
- skillDefense="1" generalHurtFactor="1" generalDefenseFactor="1"
- skillHurtFactor="1" skillDefenseFactor="1"/>
- <RateAttribute violenceRate="0" killRate="0" breakDefenseRate="0" duckRate="0"
- withstandRate="0" hitRate="0"/>
- <ValueAttribute attackOrder="0" money="0" goldBullions="0" bags="0" achievement="0"
- experience="0" vitality="0"/>
- </Role>
- </RoleRoot>
- XmlDocument xmlDoc = new XmlDocument();
- TextAsset textAsset = (TextAsset)Resources.Load("createRole");
- xmlDoc.LoadXml(textAsset.text);
- //xmlDoc.LoadXml(Application.dataPath + @"\createRole.xml");
- XmlNodeList nodeList = xmlDoc.SelectNodes("RoleRoot/Role");
- XmlNode node;
- switch (faction)
- {
- case FACTION.Monk:
- node = nodeList[0];
- break;
- case FACTION.Taoist:
- node = nodeList[1];
- break;
- case FACTION.Flower:
- node = nodeList[2];
- break;
- default:
- node = nodeList[3];
- break;
- }
- //XmlNode baseAttribute=node.SelectNodes("BaseAttribute");
- XmlNode baseAttribute = node.ChildNodes[0];
- grade = XmlConvert.ToInt32(baseAttribute.Attributes["grade"].Value);
- force = XmlConvert.ToInt32(baseAttribute.Attributes["force"].Value);
- spirit = XmlConvert.ToInt32(baseAttribute.Attributes["spirit"].Value);
- agility = XmlConvert.ToInt32(baseAttribute.Attributes["agility"].Value);
- endurance = XmlConvert.ToInt32(baseAttribute.Attributes["endurance"].Value);
- wisdom = XmlConvert.ToInt32(baseAttribute.Attributes["wisdom"].Value);
在加载xml文件的时候xmlDoc.LoadXML()可能会出现这样的错误
XmlException: Text node cannot appear in this state. Line 1, position 1.
Mono.Xml2.XmlTextReader.ReadText (Boolean notWhitespace)
Mono.Xml2.XmlTextReader.ReadContent () Mono.Xml2.XmlTextReader.Read ()