Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save List<T> to XML file

Tags:

c#

xml

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?

like image 951
inutan Avatar asked Nov 30 '11 23:11

inutan


People also ask

How do I save an XML File in Notepad?

To save the XML document, on the File menu, click Save. To exit XML Notepad, on the File menu, click Exit.


2 Answers

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();
    }
 }
like image 72
Aaron Avatar answered Oct 11 '22 02:10

Aaron


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))));
like image 37
BrokenGlass Avatar answered Oct 11 '22 02:10

BrokenGlass