【问题标题】:XMLSerialization: The type of the argument object 'Sw' is not primitiveXMLSerialization:参数对象“Sw”的类型不是原始的
【发布时间】:2014-01-05 02:58:18
【问题描述】:

我正在尝试将对象序列化为 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);
    }

例如仅包含 List&lt;Units&gt; 的对象,该对象由继承自 Units 类 (Sw) 的派生对象填充。

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

如何正确序列化这样的类?

【问题讨论】:

    标签: c# xml-serialization primitive derived-class


    【解决方案1】:

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

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

    【讨论】:

    • 很难找到一个简单的答案来解决我认为是一个简单的问题。我的代码现在可以工作了,谢谢!
    【解决方案2】:

    将对象序列化为 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 字符串,要实现上述功能,您需要导入以下库:

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

    【讨论】:

    • 我很欣赏所提供的答案,但这并不是我真正要问的。如有任何混淆,我们深表歉意。
    猜你喜欢
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2013-02-02
    • 1970-01-01
    相关资源
    最近更新 更多