When serializing/de-serializing certain classes I’ve come across the need to flag or mark certain properties as CDATA elements (due to their content). I am currently handling this like so:
<XmlElement('MessageText')> _ Public Property XmlContentLeft() As XmlCDataSection Get Dim doc As New XmlDataDocument() Dim cd As XmlCDataSection = doc.CreateCDataSection(Me.MessageText) Return cd End Get Set(ByVal value As XmlCDataSection) Me.MessageText = value.Value End Set End Property <XmlIgnore()> _ Public Property MessageText() As String Get Return _messageText End Get Set(ByVal value As String) _messageText= value End Set End Property
Now while this works great it has drawbacks — I now have duplicate properties for anything I want to be a CDATA element and I have to write extra code for these properties.
So my question is whether or not there is a better way to do this? I don’t want to have to write custom schemas or serialization routines for each class. In an ideal scenario I’d be able to add an attribute to these properties so they are automatically treated as CDATA elements.
Two things:
1) You can simplify your existing CDATA code like this:
Of course that’s actually more code than you posted, but note that your CData property is now much simpler. Also, my use of
Staticisn’t a typo or C# mistake. VB.Net has a little-knownStatickeyword for creating members in functions. This way the XmlDataDocument is only created once for the entire class and doesn’t pollute your class’s private namespace.2) The serializer should already properly escapes character data. Do you really need it to be CData? Anything you serialize should be properly deserialized to match the original, even things like code strings. The only case I can thing where you might need a CDATA section is if you have to conform to a schema that’s expecting it.