Question

I have become confused due to all of the samples using DataContractSerializer only handling one single object. I have a collection of objects, let's call it List<Ticket> tickets. I can get a the DataContractSerializer to write each object using a foreach (var ticket in tickets), but afterward I need to run a transform on the XML in order to be sure it is properly formatted. However, when using the Transform method of a XmlCompiledTransform I continue receiving the error "Unexpected end of file while parsing Name has occurred. Line 447, position 28."

Below is my code, all constructive criticism is welcome.

using (var ms = new MemoryStream())
{
    using (var writer = XmlWriter.Create(ms, settings))
    {
        var ser = new DataContractSerializer(tickets.GetType());
        writer.WriteStartDocument(true);
        writer.WriteStartElement("Tickets");
        foreach (var ticket in tickets)
        {
            ser.WriteObject(writer, ticket);
        }
        writer.WriteEndElement();
        writer.WriteEndDocument();
        ms.Position = 0;
        var xslt = new XslCompiledTransform();
        xslt.Load(xsltFp);
        using (var output = new FileStream(xmlFp, FileMode.Create))
        {
            xslt.Transform(XmlReader.Create(ms), null, output);
            output.Position = 0;
        }
    }
}
Was it helpful?

Solution

I figured it out. At the end of the foreach loop, I needed to call writer.Flush();. This effectively flushes the stream buffer before we start writing another object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top