XMLSerialization:参数对象’Sw’的类型不是原始的

我正在尝试将对象序列化为XML文件,但是我收到了上述错误。

问题似乎是包含基类列表的对象,但是由从基类派生的对象填充。

示例代码如下:

public class myObject { public myObject() { this.list.Add(new Sw()); } public List list = new List(); } public class Units { public Units() { } } public class Sw : Units { public Sw(); { } public void main() { myObject myObject = new myObject(); XmlSerializer serializer = new XmlSerializer(typeof(myObject)); TextWriter textWriter = new StreamWriter ("file.xml"); serializer.Serialize (textWriter, myObject); } 

例如,仅包含List的对象,该List由从Units类( Sw )inheritance的派生对象填充。

很抱歉没有提供我的实际代码,但涉及的对象非常复杂,这似乎是对象的唯一部分,它不会成功序列化 – 并且只有当列表包含派生类时。

我怎样才能正确序列化这样的类?

使用XmlInclude属性标记Units类将派生类作为参数传递:

 [XmlInclude(typeof(Sw))] public class Units { public Units() { } } 

将对象序列化为XML。 您可以使用以下代码

 public String SerializeResponse(SW sw) { try { String XmlizedString = null; XmlSerializer xs = new XmlSerializer(typeof(SW)); //create an instance of the MemoryStream class since we intend to keep the XML string //in memory instead of saving it to a file. MemoryStream memoryStream = new MemoryStream(); //XmlTextWriter - fast, non-cached, forward-only way of generating streams or files //containing XML data XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); //Serialize emp in the xmlTextWriter xs.Serialize(xmlTextWriter, sw); //Get the BaseStream of the xmlTextWriter in the Memory Stream memoryStream = (MemoryStream)xmlTextWriter.BaseStream; //Convert to array XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); return XmlizedString; } catch (Exception ex) { throw; } } 

该方法将返回一个XML String并创建上述函数,您需要导入以下库:

 using System.Xml; using System.Xml.Serialization; using System.IO;