How do I return XML from a Stored Procedure?
First, SqlCommand
has a ExecuteXmlReader
method, not ExecuteXMlReader
as you wrote (this is misspelling). Second, SqlCommand.ExecuteXmlReader
method returns a value of type XmlReader
, not a DataReader
as is in your example. So changing your code to:
using (XmlReader reader = cmd.ExecuteXmlReader())
{
while(reader.Read())
{
string s = reader.ReadOuterXml();
// do something with s
}
}
should solve the issue.
I had trouble with the simple approach from @Alex and better luck with this approach:
// Execute a SqlCommand that you've created earlier.
// (Don't forget your 'using' statements around SqlConnection, SqlCommand and XmlReader!)
// This is where our XML will end up
var xmlDocument = new XmlDocument();
using (XmlReader xmlReader = cmd.ExecuteXmlReader())
{
// 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
Using the reader.Read() ... var s = reader.ReadOuterXml()
somehow missed some of the elements in my longer more complex XML. I didn't bother investigating why but switching to XPathDocument
worked for me.