在Silverlight中反序列化XML字符串

时间:2014-03-03 05:46:33

标签: c# xml silverlight

InC#WinForms我可以像这样派生我的XML文件

    FileInfo fi = new FileInfo(filename);

    StreamReader file = new StreamReader(fi.FullName);


    XmlSerializer reader = new XmlSerializer(typeof(Scene));

    Scene scene = new Scene();
    scene = (Scene)reader.Deserialize(file);


    file.Close();
    file.Dispose();

但是在Silverlight中我必须下载XML并将其作为String读取,因此我需要能够反序列化XML String。不确定它是如何完成的。

这样的事情会很好

    StringReader text = new StringReader(fi.FullName);


    XmlSerializer reader = new XmlSerializer(typeof(Scene));

    Scene scene = new Scene();
    scene = (Scene)reader.Deserialize(text);

1 个答案:

答案 0 :(得分:0)

在silverlight中,

 using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(xml))) {

            DataContractSerializer dcs = new DataContractSerializer(obj.GetType());

            return (object)dcs.ReadObject(ms);

    }

Say Person是你班级的名字,

 using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(xml)))
       {
        DataContractSerializer serializer = new DataContractSerializer(person.GetType());
       return (person)serializer.ReadObject(ms);

       }