bwerks
bwerks

Reputation: 9001

DataContractSerializer: preserve string member that happens to be raw xml?

I'm a little inexperienced with the DataContract paradigm, and I'm running into a deserialization problem. I have a field that's a string, but it contains xml and it's not being deserialized correctly. I have a feeling that it's because the DCS is treating it as input to the serializer and not as an opaque string object.

Is there some way to mark a DataMember in code to say "This thing is a string, don't treat its contents as xml" similar to XmlIgnore?

Thanks!

Upvotes: 2

Views: 1920

Answers (3)

Marc Cals
Marc Cals

Reputation: 2989

There is an easy way to do, just declare the property with raw XML as XmlElement

[DataMember]
public XmlElement RawXML { private get; set; }

Upvotes: 0

bwerks
bwerks

Reputation: 9001

Turns out the easiest way to do this was just to cast the xml field coming from sql server to a varchar(max) when retrieving it from the database.

 CAST(CONVERT(XML,[RawXml],0) AS VARCHAR(MAX)) AS RawXml

In this case, the serializer seems to be ignoring it as desired. Thanks for the help though!

Upvotes: 0

marc_s
marc_s

Reputation: 755167

Well, the equivalent to [XmlIgnore] is just not putting a [DataMember] on your property/field - if you're decorating everything with [DataMember] otherwise.

But I don't see how you could tell the DataContractSerializer to treat the property as an opaque string and nothing else.

You could try to have a separate property which adds <![CDATA[ before and ]]> after your content string, and serialize that property instead of your raw XML property (by decorating that new property with the [DataMember] attribute).

Something like this:

 public string XmlContent { get; set; }

 [DataMember]
 public string XmlContentSafe 
 { 
    get { return "<![CDATA[" + XmlContent + "]]>"; }
 }

Maybe that way you can trick the DCS ? (never tried it myself - just guessing....)

Upvotes: 2

Related Questions