XML query : to XML « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="XmlQuery" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Literal id="XmlText" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Xml;
using System.Text;

public partial class XmlQuery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;

    string customerQuery = "SELECT FirstName, LastName FROM Employees FOR XML AUTO, ELEMENTS";
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand com = new SqlCommand(customerQuery, con);

    StringBuilder str = new StringBuilder();
    try
    {
      con.Open();
      XmlReader reader = com.ExecuteXmlReader();

      while (reader.Read())
      {
        if ((reader.Name == "Employees") && (reader.NodeType == XmlNodeType.Element))
        {
          reader.ReadStartElement("Employees");
          str.Append(reader.ReadElementString("FirstName"));
          str.Append(" ");
          str.Append(reader.ReadElementString("LastName"));
          str.Append("<br>");
          reader.ReadEndElement();
        }
      }
      reader.Close();
    }
    finally
    {
      con.Close();
    }
    XmlText.Text = str.ToString();
    }
}








18.56.to XML
18.56.1.XML query
18.56.2.The ASPX Page and XSLT to style the XML from SQL Server (VB)
18.56.3.The ASPX Page and XSLT to style the XML from SQL Server (C#)
18.56.4.Retrieving XML from SQL Server 2000 using FOR XML AUTO (C#)
18.56.5.Retrieving XML from SQL Server 2000 using FOR XML AUTO (VB)
18.56.6.Run a query against a SQL Server database with an XML typed column. It then displays results in a tree-view.