我正在为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(没有"数组"标记)。我怎么能实现这样的东西?
您收到任何错误吗?数组中的项可能有一些值在xml标记中无效。这样做会使xml数据为空。必须检查数组中项的有效性。xml标记名的全字符非验证。我认为使用这个例子更好:
sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8);
//Write the header
sr.WriteLine("<?xml version="1.0" encoding="utf-8" ?>");
//Write our root node
sr.WriteLine("<" + node.Text + ">");
sr.WriteLine("array");
sr.WriteLine("</" + node.Text + ">");