Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I.e., 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?

like image 420
Xavier Poinas Avatar asked Dec 22 '22 23:12

Xavier Poinas


1 Answers

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).

like image 170
Marc Gravell Avatar answered Apr 27 '23 00:04

Marc Gravell