Reputation: 526
I have list of object to store in XML Document. I am using serializing/deserializing to store and retrieve data. When i have to store new Object, i deserialise entire xml into a List and adds the new object to this List and serialize again to store it back to xml.
My question is , Is this right way to add new object, or is there any other way to add new object, I don't want to create tags manually and add because they may cause error while deserializing data.
This is what I am using right now :
public static T readXml<T>(string fileName)
{
T tempList ;
XmlSerializer deserializer = new XmlSerializer(typeof(T));
TextReader textReader = new StreamReader(fileName);
tempList = (T)deserializer.Deserialize(textReader);
textReader.Close();
return tempList;
}
public static void writeXml<T>(T tempList,string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
TextWriter textWriter = new StreamWriter(fileName);
serializer.Serialize(textWriter, tempList);
textWriter.Close();
}
Upvotes: 3
Views: 4181
Reputation: 5751
Essentially, yes, serialization is the right way to go. It is robust, reasonably flexible, and is much less work (and easier to maintain) than writing objects out "manually".
However, if the object graph that you are serializing is large, and you want to make your process more efficient, you might want to consider whether it would be possible to serialize only the new object, and then append or insert it into the existing Xml.
To insert or append new nodes, you need to load the existing xml into an XmlDocument object, find the node at which you want to add the new content, and append the new node. For example:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("MyXml.xml");
XmlDocument newDoc = new XmlDocument();
newDoc.Load("MyNewObject.xml");
//Use Xpath to specify node
XmlNode insertNode = xmldoc.SelectSingleNode("parentElement/myElement");
XmlNode newObj = newDoc.SelectSingleNode("rootElement");
insertNode.AppendChild(newObj);
xmldoc.Save("MyXml.xml");
Retrieving the xml from files is for the purposes of the example only: in the real world you may already have it in some form of stream or xml reader, or you may need to retrieve it from a database.
Upvotes: 1