Can we update existing xml files with xmlserializer?

Just wondering if we can update an already built xml file using xml serialization / deserialization in C #? Also, if the file is originally only a root node, can we update it with child nodes? (regardless of methods?)

+3


source to share


1 answer


Modifying the serialized data is against the concept of serialization - therefore XmlSerializer

does not support this.

As ryadavilli said, you can use XmlDocument or XDocument to add / modify / remove nodes manually. This is very useful if you have serialized data for objects from earlier versions and want to update those documents to a newer version.

If your current object model is no different from the serialized data, would you consider deserializing, modifying objects in memory, and serializing them again?



The only thing I can imagine is to implement IXmlSerializable

by opening both XmlReader

and XmlWriter

copying each node until you reach the "insertion point". Then use XmlSerializer

to write the data that was changed, after which you continue copying. Definitely not a turnkey solution.

As for the question in your comment - XmlSerialization is for serializing and deserializing objects, where XDocument

(xml-linq) allows you to manually compose an XML document. While the result may be the same, they essentially do different things, so it depends best on what you want to achieve.

0


source







All Articles