Just wondering if we can update an already built xml file using xml serialization/deserializtion in C#?
Also, if the file has initially only root node, can we update it with child nodes? (regardless of methods?)
Just wondering if we can update an already built xml file using xml serialization/deserializtion
Share
Changing serialized data goes against the concept of serialization – so the
XmlSerializerdoes not support this.As ryadavilli suggested you could use XmlDocument or XDocument to manually add/modify/remove nodes. This is very useful when you have serialized data of objects of earlier versions and you want to update those documents to a new version.
If your current object model isn’t different from the serialized data however, have you considered deserializing, changing the objects in memeory and serializing them back again?
The only other option I can imagine is implementing
IXmlSerializable, opening both anXmlReaderandXmlWriter, copying each node until you reach the “insertion point”. Then use theXmlSerializerto write the data that has changed, after which you continue copying. Definately not an out-of-the-box solution.As for the question in your comment – XmlSerialization is meant to serialize and deserialize objects, where
XDocument(xml-linq) allows you to manually compose an xml document. Although the result may be the same, they essentially do different things, so which one is better depends on what you want to achieve.