我有一个以 XML 格式返回数据的存储过程。 最初,根节点是表名本身。我还进行了更改,使根节点为"xml"。
在存储过程中:
SELECT * FROM mytable
FOR XML PATH('mytable'), ROOT('xml'), ELEMENTS;
读取结果时会出现相同的问题,如下所示:
string xmlresult = string.Empty;
using (var command = (SqlCommand)connection.CreateCommand())
{
command.CommandText = "sp_dosomething";
command.CommandType = CommandType.StoredProcedure;
using (XmlReader reader = command.ExecuteXmlReader())
{
while (reader.Read())
{
xmlresult = reader.ReadOuterXml();
}
}
}
例外情况是:
发送到 ExecuteXmlReader 的命令无效。 该命令必须返回 Xml 结果。
在:
at System.Data.SqlClient.SqlCommand.CompleteXmlReader(SqlDataReader ds) at System.Data.SqlClient.SqlCommand.ExecuteXmlReader()
我做错了什么?
从错误中可以清楚地看出,您得到的不是XML结果。
不要使用 ExecuteXmlReader() 尝试使用 ExecuteReader() 来获取输出并查看。这绝对不是一个好的XML。
// execute the command
reader = cmd.ExecuteReader();
// iterate through results, printing each to console
while (reader.Read())
{
Console.WriteLine("Print the data here and check output will not be XML in your case");
}