你可以将类名-XML文件名列表存在别的地方,比如说在DB或另一个XML文件中,对象是可以由名字生成的.自己查MSDN.

解决方案 »

  1.   

    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);
    }
      

  2.   

    好像类名已经存在在序列化的这个文件中了:
    <?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>
    那我在反序列化的时候是不是先要从这个文件中取出类名???这个类名就是根节点的名字吗?
      

  3.   

    好好想想,XmlSerializer是在System.Xml.dll assembly里,跟你的程序一点没关系,如果你不传入一个Type对象,它看到一个<Book>,怎么知道该生成一个什么对象?到处去找哪里有个Book类么?而且,class Book 也不一定会生成<Book>的,假如你改变其Attribute的话
      

  4.   

    saucer(思归)大哥,
    XML 序列化是将对象的公共属性和字段转换为序列格式(这里是指 XML)以便存储或传输的过程。属性定义成公共的和公共字段有什么区别,公共字段也可以直接访问,还用得着定义成属性吗?定义成属性还得写get,set?
      

  5.   

    如果我要写一个可以序列化成Xml得数据bean,我是用公共属性保存数据还是用公共字段保存好一些?
      

  6.   

    使用property的好处在于你可以验证用户设置的数据,或改变内部存储数据的方式,但如果你的对象是个纯数据结构,没什么逻辑(方法)的话,用公共变量就可以