简体   繁体   中英

Missing the end of the XML when serializing with DataContractSerializer

I have the following method that I use to serialize various objects to XML. I then write the XML to a file. All the objects have the proper [DataContract] and [DataMember] attributes.

    public static string Serialize<T>(T item)
    {
        var builder = new StringBuilder();
        var serializer = new DataContractSerializer(typeof(T));

        using (var xmlWriter = XmlWriter.Create(builder))
        {
            serializer.WriteObject(xmlWriter, item);
            return builder.ToString();
        }
    }

The serialization works fine, however, I am missing the end of the content. Ie, the string does not contain the full XML document: the end gets truncated. Sometimes the string ends right in the middle of a tag.

There does not seem to be a miximum length that would cause an issue: I have strings of 18k that are incomplete and I have strings of 80k that are incomplete as well.

The XML structure is fairly simple and only about 6-8 nodes deep.

Am I missing something?

xmlWriter isn't flushed at the point you call ToString() ; try:

    using (var xmlWriter = XmlWriter.Create(builder))
    {
        serializer.WriteObject(xmlWriter, item);
    }
    return builder.ToString();

This does the ToString() after the Dispose() on xmlWriter , meaning it will flush any buffered data to the output ( builder in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM