<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"%>
<!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>XML from SQL 2005</title>
</head>
<body>
<div id="pageContent">
<form id="form1" runat="server">
<asp:Button ID="GetDataButton" runat="server" Text="Go get data"
OnClick="GetDataButton_Click" />
<br /><br />
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
</form>
</div>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
public partial class Default : System.Web.UI.Page
{
private TreeNode Root;
protected void GetDataButton_Click(object sender, EventArgs e)
{
string connString = "SERVER=(local)\\SQLEXPRESS;ATTACHDBFILENAME=|DataDirectory|mydata.mdf;INTEGRATED SECURITY=sspi"; //;USER INSTANCE=true;";
using (SqlConnection conn = new SqlConnection(connString))
{
Root = new TreeNode("Families");
TreeView1.Nodes.Add(Root);
string cmdText = "SELECT * FROM SampleData";
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
SqlXml xml = reader.GetSqlXml(1);
ProcessData(xml);
}
reader.Close();
cmd.Connection.Close();
}
}
private void ProcessData(SqlXml xml)
{
XmlReader reader = xml.CreateReader();
TreeNode familyNode=null, parentsNode=null, childrenNode=null;
while (reader.Read())
{
if (reader.Depth == 1 && reader.NodeType == XmlNodeType.Element)
{
familyNode = new TreeNode(reader.ReadElementContentAsString());
Root.ChildNodes.Add(familyNode);
parentsNode = new TreeNode("Parents");
childrenNode = new TreeNode("Children");
familyNode.ChildNodes.Add(parentsNode);
familyNode.ChildNodes.Add(childrenNode);
}
if (reader.Depth == 2 && reader.NodeType == XmlNodeType.Element)
{
string name = reader["name"];
string role = reader["Role"];
TreeNode member = new TreeNode(name);
if (role.ToLowerInvariant().Equals("father") || role.ToLowerInvariant().Equals("mother"))
parentsNode.ChildNodes.Add(member);
else
if (role.ToLowerInvariant().Equals("child"))
childrenNode.ChildNodes.Add(member);
}
}
}
}
|