Save List<T> to XML file




So we need to save our List<T> to XML file for something. For example, for work with it in Access. C# is great for this with using System.Xml.Serialization. There are only 4 strings of code to save an XML-file. Of course I don’t describe how to get List<T> items

 

Our class is:

//Our class is:
public class logAttr {
    public string Id {get; set; }
    public string IsFailed { get; set; }
    public string User { get; set; }
    public string Pages { get; set; }
    public string Date { get; set; }
}

Writing to XML-file takes only 4 strings of code:

//
//Write List<T> to XML file
string output = "c:\\output.xml";
List<logAttr> noDupes = logsElements.Distinct().ToList();

XmlSerializer serialiser = new XmlSerializer(typeof(List<logAttr>));
TextWriter FileStream = new StreamWriter(output);
serialiser.Serialize(FileStream, noDupes);
FileStream.Close();

The result is something like this:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfLogAttr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <logAttr>
    <Id>{B4C971BB-BA85-404F-AA64-3434FD3BDEB3}</Id>
    <IsFailed>false</IsFailed>
    <User>User1</User>
    <Pages>2</Pages>
    <Date>22.03.2011 14:13:02.214000</Date>
  </logAttr>
  <logAttr>
    <Id>{29C77821-3736-4370-811E-0A71F5F033C6}</Id>
    <IsFailed>false</IsFailed>
    <User>User2</User>
    <Pages>4</Pages>
    <Date>09.04.2011 14:21:15.102000</Date>
  </logAttr>
</ArrayOfLogAttr>

 

 




No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment





MarkiMarta.com. Notes of web-specialist
Since 2009
18+