Zaman zaman çektiğimiz verilerin xml olarak alınması gerekebilir.Bu durumda yazılımcıların genelde ihtiyacı olan bu işlemi pratik bir şekilde yapabiliriz.Bu işlemi xml yayınlama, nesne listesi olarak aldığımız verilerin xml olarak incelenmesi, vb. gibi süreçleri için kullanabiliriz.
1.Bir nesneyi yada nesne listesini xml dosyası olarak serialize etme işlemi için kullanabileceğimiz metod :
public bool SerializeObject<T>(T dataList, string filePath)
{
bool isSuccess = true;
try
{
string requestString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(dataList.GetType());
using (StringWriter writer = new StringWriter())
{
xmlSerializer.Serialize(writer, dataList);
requestString = writer.ToString();
}//End Using
File.WriteAllText(filePath);
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}//End Method
2.Serialize ettiğimiz bir xml dosyasını deserialize etme işlemi için kullanabileceğimiz metod :
public List<T> DeserializeObject<T>(string filePath)
{
try
{
if (!File.Exists(filePath))
return default(List<T>);
string xmlString = File.ReadAllText(filePath);
using (MemoryStream mStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
{
mStream.Position = 0;
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
return (List<T>)serializer.Deserialize(mStream);
}
}
catch (Exception ex)
{
return default(List<T>);
}
}//End Class
1.Bir nesneyi yada nesne listesini xml dosyası olarak serialize etme işlemi için kullanabileceğimiz metod :
public bool SerializeObject<T>(T dataList, string filePath)
{
bool isSuccess = true;
try
{
string requestString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(dataList.GetType());
using (StringWriter writer = new StringWriter())
{
xmlSerializer.Serialize(writer, dataList);
requestString = writer.ToString();
}//End Using
File.WriteAllText(filePath);
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}//End Method
2.Serialize ettiğimiz bir xml dosyasını deserialize etme işlemi için kullanabileceğimiz metod :
public List<T> DeserializeObject<T>(string filePath)
{
try
{
if (!File.Exists(filePath))
return default(List<T>);
string xmlString = File.ReadAllText(filePath);
using (MemoryStream mStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
{
mStream.Position = 0;
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
return (List<T>)serializer.Deserialize(mStream);
}
}
catch (Exception ex)
{
return default(List<T>);
}
}//End Class