What does the SQL Server XML datatype translate to in .NET and how do I convert it to XmlDocument?

后端 未结 4 1369
悲&欢浪女
悲&欢浪女 2021-01-01 16:39

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

相关标签:
4条回答
  • 2021-01-01 17:03

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 17:04

    I remember casting it to a string. Feeding XmlDocument with a string works as usual then.

    0 讨论(0)
  • 2021-01-01 17:05

    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.

    0 讨论(0)
  • 2021-01-01 17:17

    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.

    0 讨论(0)
提交回复
热议问题