views:

60

answers:

4

When serializing a C# class using XmlSerializer, the attributes/elements representing the properties of the class will have the same names as they do in the source code.

I know you can override this by doing like so:

[XmlAttribute("num")]
public int NumberOfThingsThatAbcXyz { get; set; }

I'd like the generated XML for my classes to be as compact as possible, but obviously still capable of being automatically deserialized on the other side.

Is there a way to have these names minified as much as possible without having to manually think of and annotate everything with a short string? The resultant XML being easily human readable isn't a concern.

+1  A: 

In order to customize XML serialization over and above what you are able to do through the use of attributes, you will need your classes to implement the IXmlSerializable interface.

s1mm0t
+1  A: 

Hmya, watch out for micro-optimizations like this. It is incredibly hard to make them pay off with modern computing hardware. The true cost of the I/O involved with handling XML is not the amount of data, it is locating it. Bytes are cheap, transmitting them is highly optimized already. It is a disk drive read head grinding away on a server somewhere, perhaps on your own machine, that determines how fast your program runs. Once it is in the right spot, reading a byte is very nearly as expensive as reading a kilobyte. Memory works the same way.

The ultimate hint: if it would be a common optimization, they would have come up with something better than IXmlSerializable.

Hans Passant
+1  A: 

If human readability isn't an issue... why use xml at all - perhaps something like "protocol buffers" (there are C# implementations available) will give you the desired level of interoperability without this issue, including some ways of getting all the properties automatically (I can talk more about this if you are interested).

Another alternative is simply to gzip the data; xml zips surprising well, thanks to all the repeated node names.

Marc Gravell
+1  A: 

The nature of attributes implies that this can't be done. See can-attributes-be-added-dynamically-in-c# for why. Even if it could be done, I agree with Hans that it probably isn't worth it. If you are really concerned about this then you should go with one of Marc's suggestions.

drs9222