Write class instance to XML File and read file contents

You have a class and you need to save values to of the class to an xml file to be consumed later on 

[code source=”C#”]

public class TemplateInformation
{
public string StoredProcedure { get; set; }
public List<string> Parameters { get; set; }
public string TemplatePath { get; set; }
public string TemplateName { get; set; }
public String Title { get; set; }

public TemplateInformation()
{
Parameters = new List<string>();
}

}
[/code]

Save your class values to

[code source=”C#”]
public bool SaveTemplate()
{

var report = new TemplateInformation
{
StoredProcedure = "ReadReportData",
TemplateName = "Report.xls",
TemplatePath = @"c:\templates",
Title = "Monthly Income Report"
};

report.Parameters.Add("DateFrom");
report.Parameters.Add("DateTo");

XmlSerializer xs = new XmlSerializer(typeof(TemplateInformation));
TextWriter tw = new StreamWriter(@"c:\Temp\TemplateInformation.xml");
xs.Serialize(tw, report);
return true;

}
[/code]

This is the template content
[code source=”xml”]
<TemplateInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
<StoredProcedure>ReadReportData</StoredProcedure>
<Parameters>
<string>DateFrom</string>
<string>DateTo</string>
</Parameters>
<TemplatePath>c:\templates</TemplatePath>
<TemplateName>Report.xls</TemplateName>
<Title>Monthly Income Report</Title>
</TemplateInformation>
[/code]

To read the content of the xml back to your class

[code source=”c#”]
public TemplateInformation ReadTemplate()
{
TemplateInformation report;
string templateName = @"c:\Temp\TemplateInformation.xml";

XmlSerializer xs = new XmlSerializer(typeof(TemplateInformation));
using (var sr = new StreamReader(templateName))
{
report = (TemplateInformation)xs.Deserialize(sr);
}
return report;
}
[/code]


Leave a Reply