using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Xml.Serialization;
using System.IO;
public class XmlDemo : MonoBehaviour
{
// Use this for initialization
void Start()
{
string filepath = Application.dataPath + "/StreamingAssets" + "/demo.xml";
//Debug.Log("paht:" + filepath);
ListToXml(filepath);
XmlToList(filepath);
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception e)
{
return null;
}
}
void XmlToList(string path)
{
//文件是否存在
if (File.Exists(path))
{
//读取文件内容
byte[] content = File.ReadAllBytes(path);
string xml = System.Text.Encoding.Default.GetString(content);
List<Man> list2 = Deserialize(typeof(List<Man>), xml) as List<Man>;
foreach (Man man in list2)
{
Debug.Log("id:" + man.id + " name: " + man.name + " sex:" + man.sex + " address:"+man.address);
}
}
}
void ListToXml(string path)
{
List<Man> manList = new List<Man>();
manList.Add(new Man(){ id = 10001,name= "roles_girl1", sex = "girls",address = "SZ"});
manList.Add(new Man(){ id= 10002, name= "roles_girl2", sex ="girls", address = "SH"});
manList.Add(new Man(){ id= 10003, name= "roles_girl3", sex ="girls", address = "BJ"});
manList.Add(new Man(){ id= 10004, name= "roles_girl4", sex ="girls", address = "TJ"});
manList.Add(new Man(){ id= 10005, name= "roles_girl5", sex ="girls", address = "JL"});
manList.Add(new Man(){ id= 10006, name= "roles_girl6", sex ="girls", address = "CC"});
manList.Add(new Man(){ id= 10007, name= "roles_girl7", sex ="girls", address = "GC"});
manList.Add(new Man(){ id= 10008, name= "roles_girl8", sex ="girls", address = "GL"});
//开始序列化
string content = Serializer(typeof(List<Man>), manList);
//重新创建一个xml
if (File.Exists(path))
{
File.Delete(path);
}
FileStream text = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
byte[] bytec = System.Text.Encoding.UTF8.GetBytes(content);
text.Write(bytec, 0, bytec.Length);
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
//内存流
MemoryStream Stream = new MemoryStream();
//序列化类型
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化对象
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
public class Man
{
public int id { get; set; }
public string name { get; set; }
public string sex { get; set; }
public string address { get; set; }
}
}