:-$

Ryan's work blog

My Links

News

The WeatherPixie
Subscribe with Bloglines
About this blog

Tools I use:

Post Categories

Article Categories

Archives

Image Galleries

Blog Stats

Personal

Projects

Random Blogs

Random other

Reference

Web comics

Work

XmlSerializer eats default attributes

So, I'm still working with XML generation, and I discovered an interesting design choice made by the writers of XmlSerializer. My efforts from yesterday were so I could use the XmlSerializer to generate flawless XML from C# objects, without going through the bother of string manipulation. The XML it generates is well-formed, but it was leaving off an attribute ("Version"), and I wasn't sure why. I googled around and found another dev with the same problem. Craig Andera's post "DefaultValue and XmlSerializer Don't Mix?" has a quick reproduction.

If you have an attribute with a default value defined in the DTD/XSD, and the C# variable representing that attribute has that value, then the XmlSerializer chooses not to render the attribute. Anyone reading the XML must be using the same DTD/XSD, and they already know the default value, so why waste bandwidth/space by rendering that attribute?

Well, when the reader of my XML is using that missing "Version" attribute as a key for how it should process my XML, it makes a big difference. Based on the error message from the vendor, I think they are switching on that "Version" to pick a DTD, then validating against that and processing the request. It would be nice to have some kind of "RenderDefaultAttributesAnyway" flag I could set before serializing. In the end I just changed the DTD to remove the default value, and all was well.

posted on Monday, October 17, 2005 4:06 PM