Search code examples
c#.netxmlserializercdata

How to prevent XmlSerializer from escaping < and > characters


I use an XlmSerializer to serialize a dotnet object.

One property of the dotnet object is a string with this value:

"<![CDATA[<p>No Comments</p>]]>"

Once serialized to a StringWriter, all the < and > characters are converted to &lt; and &gt; including the CDATA's.

How could I stop that from happening ?


Solution

  • Don't put the CDATA in - that's the serializer's job. You've just told the serializer to make a valid XML out of the CDATA string. It does exactly that - after deserialization, you're still left with <![CDATA[<p>No Comments</p>]]>. That's exactly what you asked for! And more importantly, it's exactly what you want the serializer to do with the data - otherwise you'd be opening yourself to a world of hurt, because you'd need to ensure that the data is actually secure. In essence, you're performing double encoding.

    Instead, just put <p>No Comments</p> there - and the serializer will handle the escaping for you, to make sure it's valid XML that actually deserializes to <p>No Comments</p>.