DataContractSerializer: xml elements vs. attributes

C

cranley

I've spent hours tonight trying to figure out how I can get my WCF
DataContract to serialize properly and I'm going nuts. The
DataContractSerializer, at this point, seems to me to be very
restrictive with regards to the final xml format. For example, from
what I can see, it only serializes XML elements... but what if I want
the following:

<Group groupName="Hello" groupType="World">...</Group>

The closest I can get is the following (which is not what I want):
<Group>
<groupName>Hello</groupName>
<groupType>World</groupType>
<Group>

Is there a way to get the first one, serializing attributes instead of
elements? I can't find anything on the DataMemberAttribute attribute
that gives an option to serializing as an element or an attribute, and
I haven't been able to find any documentation anywhere discussing this
possibility.

Thanks.
 
M

Marc Gravell

I don't believe that you can...

In that scenario, perhaps use XmlSerialer instead... but note that
DataContractSerializer will happily use this (or equivalent)
internally if you remove remove the data-contract attributes and add
in the [Serializable] and [XmlAttribute] etc markers. Of course, this
changes behaviour in a number of ways...

Finally, note that DataContractSerializer also respects
IXmlSerializable - but again this would need special handling.

If you want simple metadata-based classes, then just live with what
DataContractSerializer gives you. Or perhaps run it through an xslt?

Marc
 
R

ryan baldwin

Yea, i went to bed on this last night and, as it happens so often, in
my half-sleep state I thought of an alternative solution. I shouldn't
care how the DataContractSerializer serializes the datacontract...
don't care at all. If I want to be that anal about preserving the
original states of the XML that I'm writing a DataContract class for
to send over the wire for a WCF service, then I'll simply write 2
services: 1 that returns my DataContract (which serializes as
whatever), and a second that returns the raw XML as a string.

Oooooooooooooooooh yea, that's what i'm talkin about!

Thanks for the help Marc.

- ryan.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top