<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"%>
XML from SQL 2005
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);
}
}
}
}