How to force attributes to be serialized

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I have used the xsd tool to generate a class from a schema. I then
use the XmlSerializer class to write an object to an XML file. So far
so good.

However attributes that are set to their default values are not
serialized to the XML file. However I would like to force the
serializer to write an attribute to the file, even if it is set to its
default value.

I have experimented with using a custom XmlTextWriter and also by
using XmlAttributeOverrides, but I can't figure out how to achieve
this.

Has anyone done this? Could you post some sample code?

TIA, M.
 
Yes, XmlAttributeOverrides can be used to solve your problem.
You may read one example of overview of XmlAttributeOverrides class in
MSDN. But one point may be omitted.
If the object attribute has have some xml attributes, and you only use
XmlAttributeOverrides, then those old xml attributes will be lost.
So one safe way is:
1. use reflection to get those old xml attributes
2.use XmlAttributeOverrides to filter those xml attributes not needed
3. use XmlSerializer override version

Alan
 
Back
Top