简体   繁体   中英

Serialize XML to class using Silverlight

How do I DeSerialize my XML (Text) into a Scene (Object) in SL 5.

    public static Scene Xml_to_Object(String xml_content)
    {


        Scene scene = null;


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

            scene = new Scene();
            scene = (Scene)reader.Deserialize( xml_content ); //This is wrong!

        }
        catch (Exception e)
        {

        }
        finally
        {
            file.Close();
            file.Dispose();
        }


        return scene;

    }

And where the xml_content would be

var xml_content = "<Scene>...xml stuff here .. </Scene>" ;

Scene scene = Scene.Xml_to_Object(xml_content);

public T Deserialize<T>(string xml)
{
   using( var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)) )
   {
       var serializer = new DataContractSerializer(typeof (T));
       T theObject = (T)serializer.ReadObject(stream);
       return theObject;
    }
}

The DataContractSerializer can be found in System.Runtime.Serialization . Use it like this:

 Scene scene = Deserialize<Scene>(xml_content);

First of all, your class should be have the properties required to be serialized for xml and specify element name on each property of class. eg

[Serializable]
[XmlRoot("Scene")]
[XmlType]
public class Scene
{
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("Type")]
    public string Type{ get; set; }
}

Now, you can serialize this as

 XmlSerializer xmlReq = new XmlSerializer(typeof(Scene));
 string xml = "<Scene><Name>Mahesh</Name><Type>ABC</Type></Scene>";
 var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml));
 var resposnseXml = (Scene)xmlReq.Deserialize(stream);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM