Writing CDATA in ASP.NET WebApi

2019-08-21 07:40发布

Im using the setting:

formatters.XmlFormatter.UseXmlSerializer = true;

The class i try to serailize is quite simple:

public class MyClass
{
    public MyClass()
    {
        CDATA = "<![CDATA[<link>MyLink</link>]]>"

    [XmlText]
    public string CDATA { get; set; }
}

I want this to be serialized into something like:

<MyClass>
     <![CDATA[<link>MyLink</link>]]>
</MyClass>

But instead get:

<MyClass>
     &lt;![CDATA[&lt;!link&gt;MyLink&lt;!/link&gt;]]>
</MyClass>

So how can i prevent this? Or is there a better way using the ASP.NET WebApi?

1条回答
Summer. ? 凉城
2楼-- · 2019-08-21 08:02

Looks like the answer from this question will do it:

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

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

This works with a regular XmlSerializer object, so I'd guess it works in WebAPI as well.

查看更多
登录 后发表回答