Search code examples
c#xmlxmldocumentgeneric-list

Convert Generic List of objects to SqlXml


Please do not mark as duplicate without reading through as I have been googling this and searching on stackoverflow but I cant find exactly what I want.

How do I convert a generic list of objects in c# into data type SqlXml.

Note that I am not looking to convert into xml string output.

I need this output type specifically so I can pass it in as SqlXml parameter to a stored procedure.


Solution

  • Based on John Saunders' suggestion

    MemoryStream memoryStream = new MemoryStream();
    XmlSerializer xs = new XmlSerializer(typeof(TypeOfObjectToBeConverted));
    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
    xs.Serialize(xmlTextWriter, objectToBeConverted);
    memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
    memoryStream.Position = 0;
    System.Data.SqlTypes.SqlXml obj = new System.Data.SqlTypes.SqlXml(memoryStream);