views:

627

answers:

3

Back in the days of 2.0 serialization I could create a serialized version of an object that would result in the following example:

<transactionMessage messageDate="1/1/2001 11:00PM" messageId="abc123">
    <transaction property1="Value" property2="value2" />
</transactionMessage>

I would do this with the Serializable() attribute and then appending XmlElement attributes to my items. When I use DataContract/DataMember attributes though, I get something that looks like this:

<transactionMessage>
  <messageDate>1/1/2001 11:00PM</messageDate>
  <messageId>abc123</mesageId>
  <transaction>
    <property1>Value</property1>
    <property2>Valu2</property2>
  </transaction>
</transactionMessage>

Ordinarily I wouldn't really care about the XML being generated behind the scenes, but this system will be interfacing with multiple external clients who already talk to a different system (based on the 2.0 style of serialization) and I want to keep the structure similar but bring in the added enhancements of WCF.

How can I tell the DataMember attribute to essentially make the formatting more like the first sample with attributes instead of elements for everything?

A: 

I'm not using WCF, but try adding

[XmlAttribute]

before your messageDate and messageID properties.

Chris Doggett
A: 

Well, after a little more searching it looks like it isn't possible according to this:

XMLSerializer vs DataContractSerializer

That's unfortunate that MS wouldn't give you the option to change it.

digitall
+2  A: 

The DataContract serializer was optimized for speed, and it seems the designer decided supporting attributes on XML nodes was not good for their speed requirements.

The DataContract serializer does not support attributes - if you need those, use the venerable XmlSerializer instead.

Marc

marc_s
Sounds good. I'm sure the people interacting will complain a bit, but they can get over it! Thanks for the help.
digitall