Partilhar via


Valores de coluna XML do SQL

Baixar ADO.NET

O SQL Server dá suporte ao tipo de dados xml, e os desenvolvedores podem recuperar conjuntos de resultados, incluindo esse tipo usando o comportamento padrão da classe SqlCommand. Uma coluna xml pode ser recuperada da mesma forma que qualquer coluna é recuperada (em um SqlDataReader, por exemplo), mas se você quiser trabalhar com o conteúdo da coluna como XML, deverá usar um XmlReader.

Exemplo

O aplicativo de console a seguir seleciona duas linhas, cada uma contendo uma coluna xml, da tabela Sales.Store no banco de dados AdventureWorks para uma instância do SqlDataReader. Para cada linha, o valor da coluna xml é lido usando o método GetSqlXml de SqlDataReader. O valor é armazenado em XmlReader. Observe que você deverá usar GetSqlXml em vez do método GetValue se desejar definir o conteúdo para uma variável SqlXml; GetValue retorna o valor da coluna xml como uma cadeia de caracteres.

Observação

O banco de dados AdventureWorks de exemplo não é instalado por padrão quando você instala o SQL Server. Você pode instalá-lo executando a Instalação do SQL Server.

using Microsoft.Data.SqlClient;
using System.Xml;
using System.Data.SqlTypes;

class Class1
{
    static void Main()
    {
        string c = "Data Source=(local);Integrated Security=true;" +
        "Initial Catalog=AdventureWorks; ";
        GetXmlData(c);
        Console.ReadLine();
    }

    static void GetXmlData(string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // The query includes two specific customers for simplicity's 
            // sake. A more realistic approach would use a parameter
            // for the CustomerID criteria. The example selects two rows
            // in order to demonstrate reading first from one row to 
            // another, then from one node to another within the xml column.
            string commandText =
                "SELECT Demographics from Sales.Store WHERE " +
                "CustomerID = 3 OR CustomerID = 4";

            SqlCommand commandSales = new SqlCommand(commandText, connection);

            SqlDataReader salesReaderData = commandSales.ExecuteReader();

            //  Multiple rows are returned by the SELECT, so each row
            //  is read and an XmlReader (an xml data type) is set to the 
            //  value of its first (and only) column. 
            int countRow = 1;
            while (salesReaderData.Read())
            //  Must use GetSqlXml here to get a SqlXml type. 
            //  GetValue returns a string instead of SqlXml. 
            {
                SqlXml salesXML =
                    salesReaderData.GetSqlXml(0);
                XmlReader salesReaderXml = salesXML.CreateReader();
                Console.WriteLine("-----Row " + countRow + "-----");

                //  Move to the root. 
                salesReaderXml.MoveToContent();

                //  We know each node type is either Element or Text.
                //  All elements within the root are string values. 
                //  For this simple example, no elements are empty. 
                while (salesReaderXml.Read())
                {
                    if (salesReaderXml.NodeType == XmlNodeType.Element)
                    {
                        string elementLocalName =
                            salesReaderXml.LocalName;
                        salesReaderXml.Read();
                        Console.WriteLine(elementLocalName + ": " +
                            salesReaderXml.Value);
                    }
                }
                countRow = countRow + 1;
            }
        }
    }
}

Próximas etapas