我正在尝试将对象序列化为XML文件,但我收到了上述错误。
问题似乎是包含基类列表的对象,但是由从基类派生的对象填充。
示例代码如下:
public class myObject
{
public myObject()
{
this.list.Add(new Sw());
}
public List<Units> list = new List<Units>();
}
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);
}
E.g。一个仅包含List<Units>
的对象,该对象由从Units
类(Sw
)继承的派生对象填充。
很抱歉没有提供我的实际代码,但涉及的对象非常复杂,这似乎是对象的唯一部分,它不会成功序列化 - 只有当列表包含派生类时才会这样。
如何正确序列化这样的类?
答案 0 :(得分:8)
将Units
类标记为XmlInclude
属性,将派生类作为参数传递:
[XmlInclude(typeof(Sw))]
public class Units
{
public Units()
{
}
}
答案 1 :(得分:1)
将对象序列化为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;