DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> XML學習教程 >> XML詳解 >> C#實現對象的Xml格式序列化及反序列化
C#實現對象的Xml格式序列化及反序列化
編輯:XML詳解     
化的對象的類:

[Serializable]
public class Person
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name=value;
}
}
public string Sex;
public int Age=31;
public Course[] Courses;

public Person()
{
}
public Person(string Name)
{
name=Name;
Sex="男";
}
}
[Serializable]
public class Course
{
public string Name;
[XMLIgnore]public string Description;
public Course()
{
}
public Course(string name,string description)
{
Name=name;
Description=description;
}

進行序列化及反序列化的測試類:

class Test
{
//序列化
public void Serialiaze()
{
Person c=new Person("cyj")
c.Courses=new Course[2];
c.Courses[0]=new Course("英語","交流工具")
c.Courses[1]=new Course("數學","自然科學")

XmlSerializer xs=new XMLSerializer(typeof(Person));
Stream stream = new FileStream("c:\\cyj.XML", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
xs.Serialize(stream, c);
stream.Close();
}
//反序列化
public void Deserialize()
{
XmlSerializer xs=new XMLSerializer(typeof(Person));
Stream stream = new FileStream("c:\\cyj.XML", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Person p=(Person)xs.Deserialize(stream);
Console.WriteLine(p.Name);
Console.WriteLine(p.Age.ToString());
Console.WriteLine(p.Courses.Length.ToString());
Console.Read();
}
}

格式化後XML的文檔內容為:
<?XML version="1.0"?>
<Person xmlns:xsd=http://www.w3.org/2001/XMLSchema    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <Sex>男</Sex>
  <Age>31</Age>
  <Courses>
    <Course>
      <Name>英語</Name>
    </Course>
    <Course>
      <Name>數學</Name>
    </Course>
  </Courses>
  <Name>cyj</Name>
</Person>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved