写入:
doc = new XmlDocument();
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
//2.将头部信息添加到xml文档
doc.AppendChild(declaration);
//3. 创建一个根节点
XmlNode root = doc.CreateNode(XmlNodeType.Element, "Root", null);
doc.AppendChild(root);
XmlElement path = doc.CreateElement("Path");
path.SetAttribute("path", "Resources");
root.AppendChild(path);
第一种保存方法: --> 这种方法存入的XML会带有BOM,WWW类加载会报错
doc.Save(Application.dataPath + "/Resources/data.xml");
第二种保存方法: --> 去掉BOM
StreamWriter sw = new StreamWriter(Application.dataPath + "/StreamingAssets/data.xml", false, new UTF8Encoding(false));
doc.Save(sw);
sw.Close(); --> 如果不关闭,它就永远独占该文件,无法进行其他操作
读取:
第一种,常用方法读取方法:(适合PC端读取)
void ResourcesReadAct()
{
doc = new XmlDocument();
//获取Asset下的xml文件
doc.Load(Application.dataPath + "/Resources/data.xml");
//获取xml的根节点(返回根节点)
XmlElement root = doc.DocumentElement;
//获取根节点下的某一节点
XmlNode path = root.SelectSingleNode("Path");
ResourcesText.text = path.Attributes[0].Name + ": " + path.Attributes[0].Value;
}
第二种,WWW类读取:(可是适用与PC,移动,网络端)
IEnumerator WWWreadStreaming()
{
string sPath = Application.streamingAssetsPath + "/data.xml";
WWW www = new WWW(sPath);
yield return www;
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(www.text);
XmlElement root = xmldoc.DocumentElement;
XmlNode path = root.SelectSingleNode("Path");
StreamingAssetsField.text = path.Attributes[0].Name + ": " + path.Attributes[0].Value;
}