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 


  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>();
       }

    }

Save your class values to

  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;

        }

This is the template content

<TemplateInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <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>

To read the content of the xml back to your class

 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;
       }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.