创建测试类
using System ;
using System. Collections. Generic ;
using System. Xml. Serialization ;
[ Serializable ]
public class TestSerilize
{
[ XmlAttribute ( "Id" ) ]
public int Id {
get ; set ; }
[ XmlAttribute ( "Name" ) ]
public string Name {
get ; set ; }
[ XmlElement ( "List" ) ]
public List< int > List {
get ; set ; }
}
对Xml和对象进行操作
using System. Collections. Generic ;
using System. IO ;
using System. Runtime. Serialization. Formatters. Binary ;
using System. Text ;
using System. Xml. Serialization ;
using UnityEngine ;
public class ResoucesTest : MonoBehaviour
{
void Start ( )
{
BinarySerTest ( ) ;
}
#region Xml
private void SerilizeTest ( )
{
TestSerilize testSerilize = new TestSerilize ( ) ;
testSerilize. Id = 1 ;
testSerilize. Name = "ceshi" ;
testSerilize. List = new List< int > ( ) ;
testSerilize. List. Add ( 1 ) ;
testSerilize. List. Add ( 2 ) ;
testSerilize. List. Add ( 3 ) ;
XmlSerilize ( testSerilize) ;
}
private void XmlSerilize ( TestSerilize testSerilize)
{
FileStream fileStream = new FileStream ( Application. dataPath + "/test.xml" , FileMode. Create,
FileAccess. ReadWrite, FileShare. ReadWrite) ;
StreamWriter sw = new StreamWriter ( fileStream, Encoding. UTF8) ;
XmlSerializer xml = new XmlSerializer ( testSerilize. GetType ( ) ) ;
xml. Serialize ( sw, testSerilize) ;
sw. Close ( ) ;
fileStream. Close ( ) ;
}
private TestSerilize XmlDeSerilize ( )
{
FileStream fs = new FileStream ( Application. dataPath+ "/test.xml" , FileMode. Open, FileAccess. ReadWrite, FileShare. ReadWrite) ;
XmlSerializer xs = new XmlSerializer ( typeof ( TestSerilize ) ) ;
TestSerilize testSerilize = ( TestSerilize) xs. Deserialize ( fs) ;
fs. Close ( ) ;
return testSerilize;
}
#endregion
#region Binary
private void BinarySerTest ( )
{
TestSerilize testSerilize = new TestSerilize ( ) ;
testSerilize. Id = 5 ;
testSerilize. Name = "二进制测试" ;
testSerilize. List = new List< int > ( ) ;
testSerilize. List. Add ( 10 ) ;
testSerilize. List. Add ( 18 ) ;
BinarySerilize ( testSerilize) ;
}
private void BinarySerilize ( TestSerilize testSerilize)
{
FileStream fs = new FileStream ( Application. dataPath+ "/test.bytes" , FileMode. Create, FileAccess. ReadWrite, FileShare. ReadWrite) ;
BinaryFormatter bf = new BinaryFormatter ( ) ;
bf. Serialize ( fs, testSerilize) ;
fs. Close ( ) ;
}
private TestSerilize BinaryDeserilize ( )
{
TextAsset textAsset = UnityEditor. AssetDatabase. LoadAssetAtPath < TextAsset> ( "Assets/test.bytes" ) ;
MemoryStream stream = new MemoryStream ( textAsset. bytes) ;
BinaryFormatter bf = new BinaryFormatter ( ) ;
TestSerilize testSerilize = ( TestSerilize) bf. Deserialize ( stream) ;
stream. Close ( ) ;
return testSerilize;
}
#endregion
}
测试结果
<?xml version="1.0" encoding="utf-8"?>
< TestSerilize xmlns: xsd= " http://www.w3.org/2001/XMLSchema" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" Id = " 1" Name = " ceshi" >
< List> 1</ List>
< List> 2</ List>
< List> 3</ List>
</ TestSerilize>