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;
}
You can use it as below