本文实例讲述了C# xmlSerializer简单用法。分享给大家供大家参考,具体如下:
先上实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Entity
{
public Entity()
{
}
public Entity( string c, string f)
{
name = c;
school = f;
}
public string name;
public string school;
}
|
使用时声明
1
2
|
List<Entity> entityList= null ;
XmlSerializer xs = new XmlSerializer( typeof (List<Entity>));
|
读入
1
2
3
4
|
using (StreamReader sr = new StreamReader(configPath))
{
entityList = xs.Deserialize(sr) as List<Entity>;
}
|
输出
1
2
3
4
|
using (StreamWriter sw = File.CreateText(configPath))
{
xs.Serialize(sw, entityList);
}
|
对应的xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? xml version = "1.0" encoding = "utf-8" ?>
< ArrayOfEntity xmlns:xsd = "http://www.w3.org/2001/XMLSchema" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" >
< Entity >
< Name >Alice</ Name >
< School >SJTU</ School >
</ Entity >
< Entity >
< Name >Cici</ Name >
< School >CSU</ School >
</ Entity >
< Entity >
< Name >Zero</ Name >
< School >HIT</ School >
</ Entity >
</ ArrayOfEntity >
|
希望本文所述对大家C#程序设计有所帮助。