简体   繁体   English

来自Web API的XML响应中的CData

[英]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. 我有一个ASP.NET Web API控制器,它返回一个实体,其中包含一些可能包含HTML标记的属性。 The XML formatter will by default replace all < and > with &lt ; 默认情况下,XML格式化程序将所有<和>替换为&lt; and &gt ; 和&gt; as they are not valid characters in a XML. 因为它们不是XML中的有效字符。 Now I'm wondering if it's possible to disable this replacing feature and instead wrap the content in CData tags. 现在我想知道是否可以禁用此替换功能,而是将内容包装在CData标签中。

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. 我正在寻找一种方法来实现这一点,通过配置XML格式化程序,而无需直接在控制器或实体中进行更改。 Is this possible without writing my own MediaTypeFormatter class from scratch? 如果不从头开始编写我自己的MediaTypeFormatter类,这可能吗?

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[ ... ]]> CdataContent将是<![CDATA[ ... ]]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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