we are developing wcf service using visual studio 2012. In response content added CDATA. we want to remove CDATA in soap response. Give any solution to solve this issue.
Thanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Amira BedhiafiRank #601 · 4K reputationPosted Mar 24, 2025, 10:47 AM EDT
In a WCF service, if your SOAP response contains CDATA sections (like
), it is typically because the serializer is wrapping certain string content in CDATA to prevent special characters from breaking XML structure.If you're manually serializing the response or using a custom
XmlWriter, you can configure it not to write CDATA:XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.CDataSectionElements.Clear(); // this removes CDATA wrapping XmlSerializer serializer = new XmlSerializer(typeof(YourResponseType)); using (StringWriter stringWriter = new StringWriter()) using (XmlWriter writer = XmlWriter.Create(stringWriter, settings)) { serializer.Serialize(writer, yourResponseObject); string outputXml = stringWriter.ToString(); // outputXml will not have CDATA }If you're using a
DataContract, CDATA usually comes from usingXmlCDataSectionorXmlNodetypes. Instead, use simple strings and avoid CDATA like this:[DataContract] public class YourResponseType { [DataMember] public string Message { get; set; } // Will not use CDATA }If you're using
IXmlSerializableand generating XML manually, make sure not to callWriteCData():public void WriteXml(XmlWriter writer) { writer.WriteElementString("Message", messageValue); // Avoid CDATA }If for some reason you can't avoid CDATA during serialization, you can do a string replace:
string responseXml = GetSoapResponseXml(); responseXml = responseXml.Replace("", "");Tuhin PaulRank #7 · 71.9K reputationPosted Mar 24, 2025, 2:05 PM EDT
When developing a WCF (Windows Communication Foundation) service, the SOAP response may include
sections in the XML content. This typically happens when the WCF runtime determines that certain data should be wrapped in a CDATA section to ensure it is treated as plain text and not parsed as XML. If you want to remove CDATA from the SOAP response , you can achieve this by customizing the WCF behavior or modifying how the data is serialized.1. Use a Custom Message Encoder
You can create a custom message encoder to intercept and modify the outgoing SOAP messages. This allows you to remove the CDATA sections before the response is sent to the client.
Steps:
Create a Custom Message Encoder: Implement a custom encoder by inheriting from
MessageEncoder.Modify the SOAP Response: In the
WriteMessagemethod of your custom encoder, parse the SOAP message and remove the CDATA sections.Replace the Default Encoder: Use a custom binding to replace the default encoder with your custom encoder.
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 24, 2025, 2:07 PM EDT
Example Code for a Custom Encoder:
public class NoCDataMessageEncoder : MessageEncoder { private readonly MessageEncoder _innerEncoder; public NoCDataMessageEncoder(MessageEncoder innerEncoder) { _innerEncoder = innerEncoder; } public override string ContentType => _innerEncoder.ContentType; public override string MediaType => _innerEncoder.MediaType; public override Message ReadMessage(ArraySegment buffer, BufferManager bufferManager, string contentType) { return _innerEncoder.ReadMessage(buffer, bufferManager, contentType); } public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType) { return _innerEncoder.ReadMessage(stream, maxSizeOfHeaders, contentType); } public override ArraySegment WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { // Intercept the message and remove CDATA var buffer = _innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset); var xml = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count); xml = xml.Replace("", ""); // Remove CDATA var newBuffer = Encoding.UTF8.GetBytes(xml); return new ArraySegment(newBuffer, 0, newBuffer.Length); } public override void WriteMessage(Message message, Stream stream) { _innerEncoder.WriteMessage(message, stream); } }Tuhin PaulRank #7 · 71.9K reputationPosted Mar 24, 2025, 2:08 PM EDT
2. Modify Data Contract Serialization
If the CDATA is being added due to how the data is serialized, you can control the serialization process by implementing a custom serializer or modifying the data contract.
Use
[XmlText]Attribute: If you are usingDataContractSerializer, ensure that the fields/properties are marked with[XmlText]instead of[XmlElement]. This prevents the serializer from wrapping text in CDATA.[DataContract] public class MyResponse { [DataMember] [XmlText] public string Content { get; set; } }Switch to
XmlSerializer: If you need more control over the XML output, switch toXmlSerializerinstead ofDataContractSerializer. TheXmlSerializerdoes not automatically add CDATA unless explicitly configured.[Serializable] public class MyResponse { [XmlElement] public string Content { get; set; } }Update Service Behavior: Configure the service to use
XmlSerializerby adding the following attribute to your service contract:[ServiceContract] [XmlSerializerFormat] public interface IMyService { [OperationContract] MyResponse GetData(); }Tuhin PaulRank #7 · 71.9K reputationPosted Mar 24, 2025, 2:10 PM EDT
3. Use a Custom Message Inspector
You can implement a custom message inspector to intercept and modify the outgoing SOAP messages.
Steps:
Implement
IDispatchMessageInspector: Create a class that implementsIDispatchMessageInspectorto inspect and modify the response message.public class NoCDataMessageInspector : IDispatchMessageInspector { public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { return null; } public void BeforeSendReply(ref Message reply, object correlationState) { if (reply != null) { var buffer = reply.CreateBufferedCopy(int.MaxValue); var message = buffer.CreateMessage(); using (var reader = message.GetReaderAtBodyContents()) { var body = reader.ReadOuterXml(); body = body.Replace("", ""); // Remove CDATA var modifiedMessage = Message.CreateMessage(reply.Version, null, new XmlTextReader(new StringReader(body))); modifiedMessage.Headers.CopyHeadersFrom(reply); modifiedMessage.Properties.CopyProperties(reply.Properties); reply = modifiedMessage; } } } }Apply the Inspector via Behavior: Create a custom behavior and apply the message inspector to the service.
public class NoCDataBehavior : IServiceBehavior { public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { foreach (var endpoint in serviceHostBase.ChannelDispatchers.OfType()) { foreach (var dispatcher in endpoint.Endpoints) { dispatcher.DispatchRuntime.MessageInspectors.Add(new NoCDataMessageInspector()); } } } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { } public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters) { } }Register the Behavior: Add the behavior to your service configuration.
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 24, 2025, 2:11 PM EDT
4. Modify Web.config Settings
If the CDATA is being added due to specific settings in the configuration file, you can adjust the settings to prevent CDATA from being included.
The best approach depends on your specific requirements: