1、使用XmlHelper 。提供静态拓展方法,可以将数据类与xml文件互相转换
using System;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;
/// <summary>
/// XML序列化公共处理类
/// </summary>
public static class XmlHelper
{
/// <summary>
/// 将实体对象转换成XML字符串
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="obj">实体对象</param>
public static string ToXmlString<T>(this T obj) where T : class
{
try
{
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}
catch (Exception ex)
{
throw new Exception("将实体对象转换成XML异常", ex);
}
}
/// <summary>
/// 将对象转换成本地XML文件
/// </summary>
/// <param name="obj">数据对象</param>
/// <param name="path">文件路径</param>
/// <typeparam name="T"> 数据类型 </typeparam>
/// <returns></returns>
public static bool ToXmlAndWriteTo<T>(this T obj, string path) where T : class
{
try
{
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
if (File.Exists(path))
{
File.Delete(path);
}
File.Create(path).Close();
using (StreamWriter writer = new StreamWriter(path))
{
writer.Write(sw.ToString());
writer.Close();
}
}
return true;
}
catch (Exception ex)
{
Debug.LogError("将实体对象转换成本地XML文件异常:" + ex.ToString());
return false;
}
}
/// <summary>
/// 将XML字符串转换成实体对象
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="strXML">XML</param>
public static T ToXMLObject<T>(this string strXML) where T : class
{
try
{
using (StringReader sr = new StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
throw new Exception("将XML转换成实体对象异常", ex);
}
}
/// <summary>
/// 将xml文件转换为数据对象
/// </summary>
/// <param name="path"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static T GetXMLObjectByPath<T>(string path) where T : class
{
try
{
if (!File.Exists(path))
{
return null;
}
string result = "";
using (StreamReader reader = new StreamReader(path))
{
result = reader.ReadToEnd();
}
return result.ToXMLObject<T>();
}
catch (Exception ex)
{
throw new Exception("将XML转换成实体对象异常", ex);
}
}
}
2、数据类测试小样,支持嵌套
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using UnityEngine;
[XmlRoot("测试Root", Namespace = "abc.abc", IsNullable = false)]
public class ConfigXML
{
[XmlElement("路径信息")] public string path;
public string name;
public int num;
public float rate;
public bool isOn;
[XmlArray("测试集合")]
public XMLChild[] chids;
public XMLChild[] chids2;
public int[] arr;
}
public class XMLChild
{
[XmlElement("子类字段_Name")]
public string c_name;
[XmlElement("子类字段_num")]
public int c_num;
[XmlElement("子类字段_isOn")]
public bool c_isOn;
}
3、在unity中测试
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class TestConfig : MonoBehaviour
{
private string _path;
private ConfigXML config;
private void Start()
{
_path = Path.Combine(Application.dataPath, "config.xml");
config = new ConfigXML()
{
path = "fgkjasdf",
name = "pjl",
num = 15,
rate = 1.0f,
isOn = false,
arr = new [] {1,2,3,4,5,6},
};
XMLChild[] chids = new XMLChild[5];
for (int i = 0; i < 5; i++)
{
chids[i] = new XMLChild();
chids[i].c_name = "child_" + (i + 1);
chids[i].c_num = (i + 1);
chids[i].c_isOn = (i + 1) == 2;
}
config.chids = chids;
config.chids2 = chids;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
config.ToXmlAndWriteTo(_path);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
ConfigXML xml = XmlHelper.GetXMLObjectByPath<ConfigXML>(_path);
Debug.Log(xml.name);
Debug.Log(xml.path);
Debug.Log(xml.num);
Debug.Log(xml.rate);
Debug.Log(xml.isOn);
}
}
}