Skip to content

Instantly share code, notes, and snippets.

@harrybiscuit
Last active December 20, 2015 04:18
Show Gist options
  • Save harrybiscuit/6069486 to your computer and use it in GitHub Desktop.
Save harrybiscuit/6069486 to your computer and use it in GitHub Desktop.
Iterate through XML returned by SQL Server.
public IEnumerable<XElement> GetMyThings(string sqlCommandReturningXml)
{
var connectionString = ConnectionString();//You'll have to write this method. It should return a connection string.
using (var sqlConnection = new SqlConnection { ConnectionString = connectionString })
{
sqlConnection.Open();
var cmd = SqlCommand(sqlCommandReturningXml, sqlConnection);//You'll have to write this method. It should return a SqlCommand object.
using (var reader = cmd.ExecuteXmlReader())
{
reader.Read();
while (reader.ReadState != ReadState.EndOfFile)
{
if (reader.NodeType != XmlNodeType.Element)
continue;
if (reader.Name != "MyThing")
continue;
var element = XNode.ReadFrom(reader) as XElement;
if (element != null)
{
yield return element;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment