Is it possible to create an XmlReader from output SqlParameter of type SqlDbType.Xml?

1.8k Views Asked by At

This is my parameter definition:

var param = new SqlParameter
{
    ParameterName = "@param",
    SqlDbType = SqlDbType.Xml,
    Direction = ParameterDirection.Output,
    Size = int.MaxValue
};
command.Parameters.Add(param);

Then I do:

command.ExecuteNonQuery();

And finally:

XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
return serializer.Deserialize(
    new MemoryStream(Encoding.UTF8.GetBytes(param.Value.ToString())))
    as MyClass;

Do I really need to convert to string and then byte array?

2

There are 2 best solutions below

0
On BEST ANSWER

Use Parameter.SqlValue, will return a SqlXml instance and you can use CreateReader to get an XML reader. Then use the XmlSerializer.Deserialize(XmlReader) overwrite.

If the XML is large, you should consider using CommandBehavior.SequentialAccess.

0
On

You can also do in this way:

          cnn = new SqlConnection();
          cnn.ConnectionString = "xxxxxxxxxxxxxxxxx";
          cnn.Open();

          string selectQry = "SELECT [Xml] FROM [Table1] WHERE [PK_ID] = @ID";
          cmd = new SqlCommand(selectQry, cnn);
          cmd.Parameters.AddWithValue("@ID", ID);

          XmlReader reader = cmd.ExecuteXmlReader();

          if (reader.Read())
             xdoc.Load(reader);