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?
To save the XML document, on the File menu, click Save. To exit XML Notepad, on the File menu, click Exit.
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();
}
}
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))));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With