3

我正在尝试序列化一个 Class 对象并将 xml 存储在一个字符串中,但每次我收到一条异常消息“生成 xml 文档时出错”

我试图序列化的类对象是类:

[XmlRoot("FlowOfTask")] 
public class Flow
{
    int _CurrHop = 0;

    [XmlElement("CurrentHop")]
    public int CurrentHop
    {
        get { return _CurrHop; }
        set { _CurrHop = value; }
    }

    int _TotalHops = 0;

    [XmlElement("TotalHops")]
    public int TotalHops
    {
        get { return _TotalHops; }
    }

    private List<tblTaskHop> _TaskHops;

    [System.Xml.Serialization.XmlArrayItemAttribute(ElementName = "Hop",
    IsNullable = false)]
    public List<tblTaskHop> TaskHops
    {
        get { return _TaskHops; }
    }
    public Flow()
    {

    }

    public Flow(Int64 TaskID, Int64 RoleID)
    {
        _TaskHops = HandleDB.tblTaskHopGetByTaskIDRoleID(TaskID, RoleID);
        _TotalHops = TaskHops.Count;
    }

}

我正在使用此函数进行序列化。

public static string SerializeAnObject(object item)
{

    try
    {
        string xmlText;

        //Get the type of the object
        Type objectType = item.GetType();

        //create serializer object based on the object type
        XmlSerializer xmlSerializer = new XmlSerializer(objectType);

        //Create a memory stream handle the data
        MemoryStream memoryStream = new MemoryStream();

        //Create an XML Text writer to serialize data to
        using (XmlTextWriter xmlTextWriter =
            new XmlTextWriter(memoryStream, Encoding.UTF8) { Formatting = Formatting.Indented })
        {

            //convert the object to xml data
            xmlSerializer.Serialize(xmlTextWriter, item);

            //Get reference to memory stream
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;

            //Convert memory byte array into xml text
            xmlText = new UTF8Encoding().GetString(memoryStream.ToArray());

            //clean up memory stream
            memoryStream.Dispose();
            return xmlText;
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
        return null;
    }
}

谁能帮我为什么我不能序列化这个类对象?

4

2 回答 2

2

您的序列化方法应如下所示:

public static string SerializeAnObject(Object item) {
    if (item == null)
        return null;

    var stringBuilder = new StringBuilder();
    var itemType = item.GetType();

    new XmlSerializer(itemType).Serialize(new StringWriter(stringBuilder), item);

    return stringBuilder.ToString();
}

当我像这样测试它时,上面的功能起作用:

var test = new Flow();
var xmlString = SerializeAnObject(test);
于 2012-10-29T18:47:14.127 回答
1

XML 序列化程序要求公共属性是可获取和可设置的。TotalHops 和 TaskHops 确实符合这个标准。

尝试类似:

public class Flow
{
    public int CurrentHop { get; set; }
    public int TotalHops { get; set; }
    [XmlArrayItem(ElementName = "Hop", IsNullable = false)]
    public List<tblTaskHop> TaskHops { get; set; }
}

另请注意,Type tblTask​​Hop 必须遵循相同的规则。

此外,@Yuck 具有更好的序列化器功能。

于 2012-10-29T18:56:50.903 回答