如何从存储过程返回XML?

我创建了一个返回XML的存储过程,我想在我创建的方法中返回该XML。

我有两个问题。 首先,在进行一些搜索之后,不建议使用.ExecuteScalar(); 因为它会截断超过2033个字符的字符串。

所以,我发现了一个名为ExecuteXMlReader()的函数,但是在.NET 4.0(C#)上运行的Visual Web Developer 2010 Express中,它抛出错误"System.Data.SqlClient.SqlCommand' does not contain a definition for 'ExecuteXMlReader' and no extension method 'ExecuteXMlReader' accepting a first argument of type 'System.Data.SqlClient.SqlCommand' could be found"

这是我的存储过程:

 CREATE PROCEDURE dbo.GETReport (@ReportDate date) AS SELECT * FROM ReportTbl WHERE ReportDate = @ReportDate for xml auto, elements set nocount on; RETURN 

这是我的方法:

 using System.Data; using System.Data.SqlClient; ... //connect SqlConnection conn = new SqlConnection("Data Source=localhost; User Id=foo; Password=foo; Initial Catalog=Database1"); conn.Open(); //create command SqlCommand cmd = new SqlCommand("dbo.GETReport", conn); cmd.Parameters.AddWithValue("@ReportDate", "3/24/2011"); cmd.CommandType = CommandType.StoredProcedure; DataReader rd = cmd.ExecuteXMlReader(); //this is where error is occuring //also, it is throwing an error for DataReader as well saying there is no //type of namespace with that name rd.Read(); string s = rd.ReadOuterXml(); //also dont know if this is how i should return the XML 

第二,除了ExecuteXMLReader()问题,我不知道返回一个字符串是否是首先返回XML的正确方法…是否有另一个对象类型我应该将其转换为?? 或者我应该使用的另一个function??

先感谢您!!

首先, SqlCommand有一个ExecuteXmlReader方法,而不是你写的ExecuteXMlReader (这是拼写错误)。 其次, SqlCommand.ExecuteXmlReader方法返回XmlReader类型的值,而不是示例中的DataReader 。 所以将代码更改为:

 using (XmlReader reader = cmd.ExecuteXmlReader()) { while(reader.Read()) { string s = reader.ReadOuterXml(); // do something with s } } 

应该解决这个问题。

我对@Alex的简单方法遇到了麻烦,并且运气方式更好:

 // Execute a SqlCommand that you've created earlier. // (Don't forget your 'using' statements around SqlConnection & SqlCommand!) XmlReader xmlReader = cmd.ExecuteXmlReader(); // This is where our XML will end up var xmlDocument = new XmlDocument(); // Now xmlReader has the XML but no root element so we can't // load it straight into XmlDocument :( But we can use XPathDocument // to add a node for us first. var xp = new XPathDocument(xmlReader); var xn = xp.CreateNavigator(); XmlNode root = xmlDocument.CreateElement("YourFavouriteRootElementName"); root.InnerXml = xn.OuterXml; xmlDocument.AppendChild(root); // Now xmlDocument has all the XML you have dreamed of 

使用reader.Read() ... var s = reader.ReadOuterXml()以某种方式错过了我更长的更复杂的XML中的一些元素。 我没有费心调查原因,但切换到XPathDocument对我XPathDocument