XMLSerialization: The type of the argument object 'Sw' is not primitive

流过昼夜 提交于 2019-12-12 13:28:44

问题


I'm trying to serialize an object to an XML file, but am getting the above error.

The problem seems to be with objects that contain a list of a base class but is populated by objects derived from the base class.

Example code is as follows:

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. an object that contains only a List<Units> which is populated by derived objects which inherit from the Units class (Sw).

Sorry for not providing my actual code but the objects involved are quite complex and this seems to be the only part of the object which wont successfully be serialized - and only when the list contains the derived classes.

How can I correctly serialize a class like this?


回答1:


Mark Units class with XmlInclude attribute passing your derived class as parameter:

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



回答2:


To Serialize an object to XML. you can use the following code

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;
    }
}

The method will return an XML String and to make the above function you need to import the following libraries:

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


来源:https://stackoverflow.com/questions/20917831/xmlserialization-the-type-of-the-argument-object-sw-is-not-primitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!