C# - Save List<T> to XML file

I want to save records fetched from database in an XML file, take x number of records from XML file into a custom collection List<T> process them and save updated items back into XML file.

'T' is a simple object with value type properties, something like -

public class T
{
   public int Id {get; set;}
   public string property1 {get; set;}
   public string property2 {get; set;}
}

Please guide me how can I save custom collection List<T> to XML file and vice-versa?

Also, because I am not sending out this XML file, will it make sense to go for XmlSerializer as suggested in some of the replies?

Thank you!

Answers


While you could use a serializer - and many times this is the right answer - I personally would use Linq to XML which would allow you to be more flexible on how your XML should look like, i.e. to create the following XML from a collection foos based on your class:

<Foos>
  <foo Id="1" property1="someprop1" property2="someprop2" />
  <foo Id="1" property1="another" property2="third" />
</Foos>

You could use:

var xml = new XElement("Foos", foos.Select( x=> new XElement("foo", 
                                                new XAttribute("Id", x.Id), 
                                                new XAttribute("property1", x.property1), 
                                                new XAttribute("property2", x.property2))));

Here are two methods that we use to accomplish this using the XMLSerializer:

 public static T FromXML<T>(string xml)
 {
     using (StringReader stringReader = new StringReader(xml))
     {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
     }
 }

 public string ToXML<T>(T obj)
 {
    using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        xmlSerializer.Serialize(stringWriter, obj);
        return stringWriter.ToString();
    }
 }

Need Your Help

AngularJS directive not displaying the template

javascript jquery angularjs angularjs-directive

Here is my AngularJs directive. Its' expected to show the div in the template but it shown nothing while the code is run.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.