I like XmlSerializer
, because of its fire-and-forget operation. I can give XmlSerializer
the object to serialize and the file to serialize to, and XmlSerializer
will sort out the property names and values.
XmlWriter xmlWriter = XmlWriter.Create(projectPath + "\\" + m_projectDescriptionFileName); // create new project description file (XML)
XmlSerializer xmlSerializer = new XmlSerializer(typeof(CustomerContactInfoViewModel));
xmlSerializer.Serialize(xmlWriter, contactInfo);
xmlWriter.Close();
I like LINQ to XML for its ability to navigate. Here's an example of a method for editing an object that's stored in XML (adapted from Greg's blog. There are also snippets for Insert and Delete.)
public void EditBilling(Billing billing)
{
XElement node = m_billingData.Root.Elements("item").Where(i => (int)i.Element("id") == billing.ID).FirstOrDefault();
node.SetElementValue("customer", billing.Customer);
node.SetElementValue("type", billing.Type);
node.SetElementValue("date", billing.Date.ToShortDateString());
node.SetElementValue("description", billing.Description);
node.SetElementValue("hours", billing.Hours);
m_billingData.Save(HttpContext.Current.Server.MapPath("~/App_Data/Billings.xml"));
}
As you can see, property names and values are written out in the code, unlike XmlSerializer
.
I would like to be able able to store multiple objects of different types in the same XML file (adding them at different times, not all at once). I would like to be able to deserialize them one at a time. I would like to update them one at a time.
- Is there a way to combine the LINQ navigation with fire-and-forget convenience of
XmlSerializer
? - Is
XmlSerializer
a right kind of tool for this? - Is there something better (short of setting up a proper database)?
- Am I looking for something that goes by a different name?
Any suggestion, insight or reference is really appreciated!
XmlSerializer
can infer. If I add or remove fields from my data class, I want the serialization scheme to adapt (infer) without my intervention. – Plainclothesman