the deserializer needs to know what type of object to instantiate, if you don't pass a type in, how does it know it should create a Book object if it sees <Book>? think about it, XmlSerializer lives in System.Xml.dll assembly, it does not know the type "Book" exists, should it search through your AppDomain or your hard disk to find the right assembly which contains the type Book?static void Main(string[] args) { string sFile = "INPUT-Test-004.xml"; Book BookObject = new Book(); XmlSerializer ser = new XmlSerializer(typeof(Book)); TextWriter writer = new StreamWriter(sFile); BookObject.Title = "Practical LotusScript"; BookObject.ISBN = "1884777767 "; BookObject.Publisher = "Manning Publications"; BookObject.Author = "Liming"; ser.Serialize(writer, BookObject); writer.Close();Console.Write("enter to read the data"); Console.ReadLine(); XmlSerializer ser2 = new XmlSerializer(typeof(Book)); System.IO.FileStream fs2 = new System.IO.FileStream(sFile, FileMode.Open); System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(fs2); Book BookObject2 = (Book)(ser2.Deserialize(reader)); fs2.Close(); Console.WriteLine(BookObject2.Author); }
好好想想,XmlSerializer是在System.Xml.dll assembly里,跟你的程序一点没关系,如果你不传入一个Type对象,它看到一个<Book>,怎么知道该生成一个什么对象?到处去找哪里有个Book类么?而且,class Book 也不一定会生成<Book>的,假如你改变其Attribute的话
saucer(思归)大哥, XML 序列化是将对象的公共属性和字段转换为序列格式(这里是指 XML)以便存储或传输的过程。属性定义成公共的和公共字段有什么区别,公共字段也可以直接访问,还用得着定义成属性吗?定义成属性还得写get,set?
{
string sFile = "INPUT-Test-004.xml";
Book BookObject = new Book();
XmlSerializer ser = new XmlSerializer(typeof(Book));
TextWriter writer = new StreamWriter(sFile);
BookObject.Title = "Practical LotusScript";
BookObject.ISBN = "1884777767 ";
BookObject.Publisher = "Manning Publications";
BookObject.Author = "Liming";
ser.Serialize(writer, BookObject);
writer.Close();Console.Write("enter to read the data");
Console.ReadLine(); XmlSerializer ser2 = new XmlSerializer(typeof(Book));
System.IO.FileStream fs2 = new System.IO.FileStream(sFile, FileMode.Open);
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(fs2);
Book BookObject2 = (Book)(ser2.Deserialize(reader)); fs2.Close(); Console.WriteLine(BookObject2.Author);
}
<?xml version="1.0" encoding="utf-8"?>
<Book xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Title>Practical LotusScript</Title>
<Author>Tony</AuthorObject>
<ISBN>1884777767 </ISBN>
<RetailPrice>43.95</RetailPrice>
<Publisher>Manning Publications</Publisher>
</Book>
那我在反序列化的时候是不是先要从这个文件中取出类名???这个类名就是根节点的名字吗?
XML 序列化是将对象的公共属性和字段转换为序列格式(这里是指 XML)以便存储或传输的过程。属性定义成公共的和公共字段有什么区别,公共字段也可以直接访问,还用得着定义成属性吗?定义成属性还得写get,set?