已经使用xsd.exe生成了cs代码,也已经使用这个cs代码通过系列化方式生成了XML请问如何通过这个CS代码读取XML数据。并且把XML数据放到对应的Class

解决方案 »

  1.   

    通过反序列化的方式
    // 假设你生成的 XSD 类叫 MyXSDusing(FileStream stream = File.Open("myxsd.xml"))
    {
        XmlSerializer xs = new XmlSerializer(typeof(MyXSD))
        MyXSD myxsd = (MyXSD)xs.Deserialize(stream);
    }
      

  2.   

    http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize(VS.71).aspxhttp://geekswithblogs.net/timh/archive/2006/02/09/68857.aspx
      

  3.   

    我回复的内容怎么没了?可以通过反序列化实现,假设 XSD 生成的类叫 MyXSD。using(FileStream fs = File.OpenRead("mydata.xml"))
    {
        XmlSerializer xs = new XmlSerializer(typeof(MyXSD));
        MyXSD mx = (MyXSD)xs.Deserialize(fs);
    }
      

  4.   

    mXML = "<ClientHello>\r\n  <Version>1.0</Version>\r\n  <Msg>Hello server</Msg>\r\n  <MyName>U_</MyName>\r\n</ClientHello>";mXML = "<?xml version=\"1.0\"?>\r\n<ClientHello xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <Version>1.0</Version>\r\n  <Msg>Hello server</Msg>\r\n  <MyName>U_</MyName>\r\n</ClientHello>";
    System.IO.Stream stream = new System.IO.MemoryStream();
    byte[] array = System.Text.Encoding.Default.GetBytes(mXML);stream.Write(array, 0, (int)stream.Length);
    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(ClientHello));
    ClientHello mx = (ClientHello)xs.Deserialize(stream);
    这两个的XML,都不能过反系列化,第二个可是通过XSD系列化出来的,都是提示没有根元素,请问要怎么处理
      

  5.   

    以上代码有点错误,但是修正后还是不行stream.Write(array, 0, (int)array.Length);
    System.IO.Stream stream = new System.IO.MemoryStream();
    byte[] array = System.Text.Encoding.Default.GetBytes(mXML);stream.Write(array, 0, (int)array.Length);
    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(ClientHello));
    ClientHello mx = (ClientHello)xs.Deserialize(stream);
      

  6.   

    System.IO.Stream stream = new System.IO.MemoryStream();
    byte[] array = System.Text.Encoding.Default.GetBytes(mXML);stream.Write(array, 0, (int)array.Length);stream.Seek(0, SeekOrigin.Begin);   // 加这一行
    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(ClientHello));
    ClientHello mx = (ClientHello)xs.Deserialize(stream);