9

我正在编写一个返回动态构造的属性包的 Web API Web 服务。是否有任何有效的序列化程序或如何将动态序列化为 XML 的方法?我试图寻找任何好的建议,但没有找到任何有用的建议。

4

1 回答 1

22

We solved it by creating a custom XML formatter.

This isn't an ideal solution but it works.

In the Global.asax

GlobalConfiguration.Configuration.Formatters.Add(new CustomXmlFormatter());
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Create a new class called CustomXmlFormatter

using System;
using System.IO;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace EMP.WebServices.api.Formatters
{
    public class CustomXmlFormatter : MediaTypeFormatter
    {
        public CustomXmlFormatter()
        {
            SupportedMediaTypes.Add(
                new MediaTypeHeaderValue("application/xml"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
        }

        public override bool CanReadType(Type type)
        {
            if (type == (Type)null)
                throw new ArgumentNullException("type");

            return true;
        }

        public override bool CanWriteType(Type type)
        {
            return true;
        }

        public override Task WriteToStreamAsync(Type type, object value,
            Stream writeStream, System.Net.Http.HttpContent content,
            System.Net.TransportContext transportContext)
        {
            return Task.Factory.StartNew(() =>
                {
                        var json = JsonConvert.SerializeObject(value);

                        var xml = JsonConvert
                            .DeserializeXmlNode("{\"Root\":" + json + "}", "");

                        xml.Save(writeStream);
                });
        }
    }
}
于 2013-09-30T01:32:44.223 回答