如何序列化/ C#中反序列化可选的XML枚举
1个回答
展开全部
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
[Serializable]
public class Employee {
public String Name { get; set; }
public String DepartmentName { get; set; }
public String Post { get; set; }
[XmlIgnore]
public int Age { get; set; }
}
class Program{
static void Main(string[] args){
Employee firstEmp = new Employee() { Name = "光头强", DepartmentName = "大数据技术中心", Post = "人工智能专家" };
Employee secondEmp = null;
XmlSerializer xs = new XmlSerializer(typeof(Employee));
// 序列化为xml
using (TextWriter tw=new StreamWriter("employee.xml")){
xs.Serialize(tw, firstEmp);
tw.Flush();
tw.Close();
}
// 把xml反列化对象
using (TextReader tr = new StreamReader("employee.xml")){
secondEmp= xs.Deserialize(tr) as Employee;
tr.Close();
}
if (secondEmp != null){
Console.WriteLine("Name="+secondEmp.Name+" Department Name="+secondEmp.DepartmentName+" Post="+secondEmp.Name);
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
[Serializable]
public class Employee {
public String Name { get; set; }
public String DepartmentName { get; set; }
public String Post { get; set; }
[XmlIgnore]
public int Age { get; set; }
}
class Program{
static void Main(string[] args){
Employee firstEmp = new Employee() { Name = "光头强", DepartmentName = "大数据技术中心", Post = "人工智能专家" };
Employee secondEmp = null;
XmlSerializer xs = new XmlSerializer(typeof(Employee));
// 序列化为xml
using (TextWriter tw=new StreamWriter("employee.xml")){
xs.Serialize(tw, firstEmp);
tw.Flush();
tw.Close();
}
// 把xml反列化对象
using (TextReader tr = new StreamReader("employee.xml")){
secondEmp= xs.Deserialize(tr) as Employee;
tr.Close();
}
if (secondEmp != null){
Console.WriteLine("Name="+secondEmp.Name+" Department Name="+secondEmp.DepartmentName+" Post="+secondEmp.Name);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询