We have a column in the database that has a type of xml
. I am reading this information via the .net SqlDataReader
, but I\'m not sure what to cast i
I use this method myself, using SqlCommand.ExecuteXmlReader();
XmlDocument xdoc = new XmlDocument();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
XmlReader reader = command.ExecuteXmlReader();
if (reader.Read())
{
xdoc.Load(reader);
}
}
I remember casting it to a string. Feeding XmlDocument with a string works as usual then.
It translates to SqlXml and you can get an XmlReader
with SqlXml.CreateReaderfrom it. You'd have to use SqlDataReader.GetSqlXmlmethod to get the type instead of a string.
For example:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
SqlXml xmlData =
reader.GetSqlXml(0);
XmlReader xmlReader = xmlData.CreateReader();
xmlReader.MoveToContent();
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
string elementName = xmlReader.LocalName;
xmlReader.Read();
Console.WriteLine(elementName + ": " + xmlReader.Value);
}
}
}
UPDATE: To answer a helpful comment from @Wiktor Zychla
The performance of this approach is better and can be a lot better when dealing with large XML fields because SqlReader.GetString
will load the field content into a string first while SqlReader.GetSqlXml
creates an XmlReader from the stream directly. That can be quickly verified with a look at System.Data in Reflector or a similar tool.
Sure, there's a System.Xml namespace:
The System.Xml namespace provides standards-based support for processing XML.
To use it, though, you'll probably have to add it as a reference in your project. Microsoft has instructions for doing this in Visual Studio.