Reputation:
I storage a set of user provided data in a file. When I took over the project, everything was saved to a plain text file. I redesigned it and now, the storage is an XML file. When the process starts, I read the XML file using XDocument and XElement classes. When I've obtained the values I put them in a constructor of my executing object.
I wonder if there's a way to automagically read in the XML data so that it, sort of, transforms (or is converted to) an instance of my object.
So, instead of:
XElement fromFile = XElement.Load(pathName);
XElement newStuff =
new XElement("MainNode",
new XElement("SubNode1", myObject.valueOfSubNode1),
new XElement("SubNode2", myObject.valueOfSubNode2));
fromFile.ReplaceAll(newStuff);
XmlTextWriter writer = ...;
fromFile.Save(writer);
I'd like to "store" the instance of myObject itself. I'm assuming that's possible. I have no idea how or even where to start.
Upvotes: 1
Views: 1578
Reputation: 44605
to serialize a type to XML:
public static string Serialize<T>(T data)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter sw = new StringWriter();
xmlSerializer.Serialize(sw, data);
return sw.ToString();
}
to deserialize from XML back into your object:
public static object DeSerialize<T>(string data)
{
StringReader rdr = new StringReader(data);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
var result = (T)xmlSerializer.Deserialize(rdr);
return result;
}
also have a look here: C# XML Serialization/DeSerialization
Upvotes: 1