[英]XML Serializer serializing a Class that extend List
我有一个ac#项目,其中包含接口和扩展该接口的类。 显然,Serializer不喜欢Interface,因此,我必须创建一个扩展List的集合类,这可以工作,但是我需要排除List根。 请在下面找到代码示例
public interface ICreature
[XmlRoot("Creature")]
public class Man : ICreature
[XmlRoot("Creature")]
public class Alien : ICreature
public class CreatureCollection : List<ICreature>, IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
}
public void WriteXml(XmlWriter writer)
{
foreach (ICreature aCreature in this)
{
XmlSerializer xmlSerializer = new XmlSerializer(aCreature.GetType());
xmlSerializer.Serialize(writer, aCreature);
}
}
}
public class Something{
...
public CreatureCollection{get;set;}
}
public void main(){
Something sm = new Something();
sm.CreatureCollection.Add(new Alien());
sm.CreatureCollection.Add(new Man());
}
XML输出:
<Something>
<CreatureCollection>
<Creature></Creature>
<Creature></Creature>
</CreatureCollection>
</Someting>
需要的输出:
<Something>
<Creature></Creature>
<Creature></Creature>
</Someting>
请帮忙!...谢谢!
像这样添加XmlElement
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CreatureCollection creatures = new CreatureCollection() { creatures = new List<string>() { "", "", "" } };
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
XmlWriter xWriter = XmlWriter.Create(writer);
creatures.WriteXml(xWriter);
}
}
public class CreatureCollection : List<string>, IXmlSerializable
{
public List<string> creatures { get; set; }
public System.Xml.Schema.XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
}
public void WriteXml(XmlWriter writer)
{
Something something = new Something() { creatures = new List<string>() };
something.creatures.AddRange(creatures);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Something));
xmlSerializer.Serialize(writer, something);
}
}
[XmlRoot("Something")]
public class Something
{
[XmlElement("Creature")]
public List<string> creatures { get; set; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.