2011-03-24 131 views
16

我創建了一個返回XML的存儲過程,我也希望在創建的方法中返回該XML。如何從存儲過程返回XML?

我有兩個問題。首先,在進行一些搜索之後,建議不要使用.ExecuteScalar();,因爲它會截斷2033個字符以上的字符串。

於是,我找到了一個叫ExecuteXMlReader()功能,但在Visual Web Developer 2010和學習表達對.NET 4.0(C#)運行時,它拋出錯誤"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的正確方法...是否有另一個對象類型我應該將其轉換爲?或者我應該使用另一個函數?

預先感謝您!

回答

25

首先,SqlCommand有一個ExecuteXmlReader方法,而不是你寫的ExecuteXMlReader(這是拼寫錯誤)。其次,SqlCommand.ExecuteXmlReader方法返回的值類型爲XmlReader,而不是DataReader,如同您的示例中所示。因此將您的代碼更改爲:

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

應解決問題。

+0

工作很好,但問題很快..有沒有辦法將XML作爲XML返回而不是字符串? – AngeloS 2011-03-24 19:35:13

+2

'XmlReader'是讀取任何XML的底層方法。例如,您將使用它來加載XDocument或XmlDocument,使用XDocument.Load(reader)。 – 2011-03-24 19:38:12

+2

@Angelo,你可以使用類似於'XmlDocument document = new XmlDocument(); document.Load(reader);'或者像@John所說的那樣使用'XDocument.Load(reader)'。謝謝,@約翰! – Alex 2011-03-24 19:42:18

3

我曾與simple approach從@Alex和更好的運氣麻煩this approach

// 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爲我工作。