Search code examples
sql-serverado.net

Read XML from SQL Server using OleDbDataReader


I'm stuck trying to read XML data from SQL Server using OleDb.

private static void Main(string[] args){
   var con = new OleDbConnection("Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Temp");
   var cmd = new OleDbCommand(
                "SELECT [Id] ,[Description] FROM [Temp].[dbo].[SomeTable] where [Id]= 1 for xml path, root('root')", con);

   con.Open();
   byte[] result = null;

   OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

   while (reader.Read()){
       result = (byte[]) reader[0];
   }

   MemoryStream stream = new MemoryStream(result);
   stream.Position = 0;

   XmlDocument doc = new XmlDocument();
   doc.Load(stream);

   Console.Out.WriteLine(doc.OuterXml);
}

It fails saying that data is malformed. If I convert the byte array to string I see a lot of "strange " characters. What I'm doing wrong?


Solution

  • Since the result is direct XML I believe you are facing issue.You need to get the result in row-set instead of scalar. Read as String, Use LoadXML instead of stream.

    Below is the code I changed.

        private static void Main(string[] args)
        {
            var con = new OleDbConnection("Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Temp");
            var cmd = new OleDbCommand(
                         "Select (SELECT [Id] ,[Description] FROM [Temp].[dbo].[SomeTable] where [Id]= 1 for xml path, root('root')) AS XML", con);
    
            con.Open();
            string result = string.Empty;
    
            OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    
            if (reader.Read())
            {
                result = reader[0].ToString();
            }
            con.Close();
         
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);
    
            Console.Out.WriteLine(doc.OuterXml);
        }