Microsoft’s KB article Q310378: XML Data Is Truncated When You Use SqlDataReader, and all of a sudden it became clear:
When you read Extensible Markup Language (XML) data from Microsoft SQL Server by using the SqlDataReader object, the XML in the first column of the first row is truncated at 2,033 characters. You expect all of the contents of the XML data to be contained in a single row and column.
This behavior occurs because, for XML results greater than 2,033 characters in length, SQL Server returns the XML in multiple rows of 2,033 characters each.
The keyword here is multiple. If you call ExecuteScalar
you have no way of getting anything but the very first column of the very first row, so this method is a dead end.
Another KB article, Q316701: Use the ExecuteXmlReader Method of the SqlCommand Class in Visual C# .NET shows how to bypass this problem by reading in a loop until all rows are read. I ended up with this:
connection.Open (); rdr = command.ExecuteXmlReader (); rdr.Read (); while (rdr.ReadState != ReadState.EndOfFile) { result += rdr.ReadOuterXml (); } rdr.Close ();
For greater efficiency I’d use a StringBuilder
here to concatenate chunks of text.