简体   繁体   中英

CData in XML response from Web API

I have an ASP.NET Web API controller which returns an entity with some attributes that might contain HTML markup. The XML formatter will by default replace all < and > with &lt ; and &gt ; as they are not valid characters in a XML. Now I'm wondering if it's possible to disable this replacing feature and instead wrap the content in CData tags.

So instead of:

<entity ...>
  <element>
    Some text with &lt;strong&gt;html&lt;/strong&gt;
  </element>
</entity>

I want this:

<entity ...>
  <element>
    <![CDATA[
      Some text with <strong>html</strong>
    ]]>
  </element>
</entity>

I'm looking for a way to achieve this by configuring the XML formatter and without the need of making changes directly in the controller or entity. Is this possible without writing my own MediaTypeFormatter class from scratch?

I achieved it with that snippet:

[XmlIgnore]
public string Content { get; set; }

[DataMember]
[XmlText]
public XmlNode[] CdataContent
{
  get => new XmlNode[] { new XmlDocument().CreateCDataSection(Content) };
  set => Content = value[0].Value;
}

CdataContent will be <![CDATA[ ... ]]>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM