XmlSerializer xs = new XmlSerializer(MyObject.GetType());
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, MyObject);
StreamWriter sw = System.IO.File.CreateText("C:\\tmp\\custData.xml");
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string theContent = sr.ReadToEnd();
sw.Write(theContent);
sw.Close();
sw.Dispose();
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, MyObject);
StreamWriter sw = System.IO.File.CreateText("C:\\tmp\\custData.xml");
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string theContent = sr.ReadToEnd();
sw.Write(theContent);
sw.Close();
sw.Dispose();
Deserialize an XML file to an object (assuming that you have the classes created):
Object obj = new object();
XmlSerializer xs = new XmlSerializer(objectDestination.GetType());
FileStream fs = new FileStream(pathToXML, FileMode.Open);
XmlReader xr = new XmlTextReader(fs);
obj = xs.Deserialize(xr);
fs.Close();
Here we have a method that takes the XML string as paramater returns an object of type T:
XmlSerializer xs = new XmlSerializer(objectDestination.GetType());
FileStream fs = new FileStream(pathToXML, FileMode.Open);
XmlReader xr = new XmlTextReader(fs);
obj = xs.Deserialize(xr);
fs.Close();
public static T DeserializeXMLToObject(string objectAsXml)
{
XmlSerializer xs = new XmlSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(objectAsXml)); XmlReader xr = new XmlTextReader(ms); T obj = (T)xs.Deserialize(xr); return obj;
}
{
XmlSerializer xs = new XmlSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(objectAsXml)); XmlReader xr = new XmlTextReader(ms); T obj = (T)xs.Deserialize(xr); return obj;
}
No comments:
Post a Comment