我正在为 Web API 应用程序开发自定义 XmlFormatter。我希望它以不同的方式处理“IEnumerable”元素。这是代码:
class CustomXmlFormatter : XmlMediaTypeFormatter
{
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext, System.Threading.CancellationToken cancellationToken)
{
XmlSerializer serializer;
return Task.Factory.StartNew(() =>
{
if ((typeof(IEnumerable<object>)).IsAssignableFrom(type))
{
XmlWriter writer = XmlWriter.Create(writeStream);
writer.WriteStartElement("array");
/* foreach (object o in (IEnumerable<object>)value)
{
serializer = new XmlSerializer(o.GetType());
serializer.Serialize(writeStream, o);
}*/
writer.WriteEndElement();
}
else
{
serializer = new XmlSerializer(type);
serializer.Serialize(writeStream, value, xsn);
}
});
这个想法是,当它接收到一个 List 时,它会写入一个“array”标签,然后序列化 List 的所有元素。我已经评论了 foreach 循环以简化问题。
问题是,当代码被执行时,它会写入一个空的 XML(没有“数组”标签)。我怎么能实现这样的东西?