Write XML to file

This code snippet is related to xml serialization. In many cases, we need to write serialized object into XML.

Following code shows how to write object into XML.


using (StreamWriter writer = new StreamWriter(FileName, false))
{
writer.Write(reportDescriptor.ToString());
}


In above code reportDescriptor is a object of ReportDescriptor class.

Following code converts xml into string. As well as write xml by encoding UTF-8.

public override string ToString()
{
string sdata = string.Empty;
XmlSerializer x = new XmlSerializer(this.GetType());
XmlWriterSettings xwSettings = new XmlWriterSettings();
xwSettings.Encoding = Encoding.UTF8;
xwSettings.Indent = true;
xwSettings.IndentChars = "\t";
xwSettings.NewLineChars = Environment.NewLine;
xwSettings.ConformanceLevel = ConformanceLevel.Document;

using (MemoryStream stream = new MemoryStream())
{
using (XmlWriter xw = XmlTextWriter.Create(stream, xwSettings))
{
x.Serialize(xw, this);
sdata = Encoding.UTF8.GetString(stream.ToArray());
if (sdata.Length > 0 && sdata[0] != '<')
sdata = sdata.Substring(1, sdata.Length - 1);

}

}
return sdata;
}


Comments

Author: Phagu Mahato10 Jan 2014 Member Level: Gold   Points : 7

You can use it as below

var xmlString = SerializationUtil.ToXml(obj);
var obj = SerializationUtil.FromXml(xmlString);

public static class Serialize
{
private static readonly Dictionary _serializersCache = new Dictionary();

private static XmlSerializer GetSerializer(Type type)
{
XmlSerializer xmls;
if (!_serializersCache.TryGetValue(type, out xmls))
{
xmls = new XmlSerializer(type);
_serializersCache[type] = xmls;
}
return xmls;
}

public static string ToXml(T obj)
{
var xmls = GetSerializer(typeof(T));
var Strbuild = new StringBuilder();
using (var writer = new StringWriter(Strbuild))
{
xmls.Serialize(writer, obj);
writer.Close();
}
return Strbuild.ToString();
}
public static T FromXml(string xml)
{
T a;
var xmls = GetSerializer(typeof(T));
using (var reader = new StringReader(xml))
{
a = (T)xmls.Deserialize(reader);
reader.Close();
}
return a;
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: