<%@ 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();
}
}