如何在SL 5中将我的XML(文本)转换为场景(对象)。
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;
}
xml_content将在哪里
var xml_content = "<Scene>...xml stuff here .. </Scene>"
;
场景场景= Scene.Xml_to_Object(xml_content);
答案 0 :(得分:2)
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;
}
}
可以在DataContractSerializer
中找到System.Runtime.Serialization
。像这样使用它:
Scene scene = Deserialize<Scene>(xml_content);
答案 1 :(得分:0)
首先,您的类应具有为xml序列化所需的属性,并在类的每个属性上指定元素名称。 e.g。
[Serializable]
[XmlRoot("Scene")]
[XmlType]
public class Scene
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Type")]
public string Type{ get; set; }
}
现在,您可以将其序列化为
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);