Web API – 动态到XML序列化

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

我们通过创建自定义XML格式化程序来解决它。

这不是一个理想的解决方案,但它有效。

Global.asax

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

创建一个名为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); }); } } }