XMLSerializer无法正常工作。没有例外

时间:2015-01-08 06:34:09

标签: c# asp.net-mvc xml-serialization

我使用下面的代码来序列化一个类。

    public static string SerializeToString<T>(this T toSerialize)
    {
        XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());
        using (StringWriter textWriter = new StringWriter())
        {
            serializer.Serialize(textWriter, toSerialize);
            return textWriter.ToString();
        }

    }

此代码间歇性地工作。有时它返回序列化字符串,有时不返回。任何地方都不例外。

我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

在致电StringWriter之前,您需要Flush ToString()

public static string SerializeToString<T>(this T toSerialize)
{
    XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());
    using (StringWriter textWriter = new StringWriter())
    {
        serializer.Serialize(textWriter, toSerialize);
        textWriter.Flush();
        return textWriter.ToString();
    }

}

当数据写入StringWriter时,它首先被写入内部缓冲区。调用ToString()时无法识别内部缓冲区中的数据。

或者,您可以使用以下代码:

    public static string SerializeToString<T>(this T toSerialize)
    {
        XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());

        StringBuilder stringBuilder = new StringBuilder();

        using (StringWriter textWriter = new StringWriter(stringBuilder))
        {
            serializer.Serialize(textWriter, toSerialize);
        }

        return stringBuilder.ToString();
    }

此处StringWriter将其数据写入StringBuilder。通过使用using关键字,StringWriter在离开块时自动关闭,迫使StringWriter将其数据刷新到给定的StringBuilder