473,661 Members | 2,429 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recursive function to get parent child relationship

RJN
Hi

I need help in writing a recursive function. My table structure is as
below.

InstanceId LevelId ParentId
100 1 null
101 2 100
102 3 101
103 4 102
104 5 103
105 5 104
106 5 104

From the above example, 100 is the root node which has a child 101, 101
has a child 102 and so on. Given a instanceid I want to get all the
child below that having levelid = 5. So if I give InstanceId=100, then I
should get a list of 104, 105, 106. If I pass the instance id 104, then
I should get 105 and 106. How I can I write a recursive function for
this?

Also I want to construct the xml tree structure. So passing in Instance
Id, I should get the immediate child below that and so on. If instance
id is 100, then there should be one leaf node 101 which will have
another leaf node 102 and so on. Can anyone help me?

Thanks

rjn

*** Sent via Developersdex http://www.developersdex.com ***
Nov 21 '05 #1
2 5984
RJN,
Assuming your data is already in a DataTable or DataSet, there are a couple
of ways to do this, the "easiest" is to let the DataSet itself write the
Tree.

Here is an example of both methods:

Private Shared Function CreateTable() As DataTable
Dim table As New DataTable("RJN" )
table.Columns.A dd("InstanceId" , GetType(Integer ))
table.Columns.A dd("LevelId", GetType(Integer ))
table.Columns.A dd("ParentId", GetType(Integer ))

table.Rows.Add( New Object() {100, 1, Nothing})
table.Rows.Add( New Object() {101, 2, 100})
table.Rows.Add( New Object() {102, 3, 101})
table.Rows.Add( New Object() {103, 4, 102})
table.Rows.Add( New Object() {104, 5, 103})
table.Rows.Add( New Object() {105, 5, 104})
table.Rows.Add( New Object() {106, 5, 104})
Return table
End Function

Private Shared Sub WriteDataSet(By Val table As DataTable)
Dim ds As New DataSet("ds")
table.PrimaryKe y = New DataColumn() {table.Columns( "InstanceId ")}

ds.Tables.Add(t able)

Dim relation As New DataRelation("C hildren",
table.Columns(" InstanceId"), table.Columns(" ParentId"))
relation.Nested = True

ds.Relations.Ad d(relation)

ds.WriteXml("rj n.xml")
End Sub

Private Shared Sub WriteXml(ByVal table As DataTable)
Dim writer As New Xml.XmlTextWrit er("rjn.xml",
System.Text.Enc oding.UTF8)
writer.WriteSta rtDocument()
WriteXmlTree(wr iter, table, Nothing)

writer.WriteEnd Document()

writer.Close()
End Sub

Private Shared Sub WriteXmlTree(By Val writer As Xml.XmlTextWrit er, ByVal
table As DataTable, ByVal instanceId As Object)
Dim children As New DataView(table)
If instanceId Is Nothing Then
children.RowFil ter = "ParentId Is Null"
Else
children.RowFil ter = "ParentId = " & DirectCast(inst anceId,
Integer)
End If
For Each row As DataRowView In children
writer.WriteSta rtElement("row" )
writer.WriteEle mentString("Ins tanceId",
row.Row!Instanc eId.ToString())
writer.WriteEle mentString("Lev elId", row.Row!LevelId .ToString())
writer.WriteEle mentString("Par entId",
row.Row!ParentI d.ToString())
WriteXmlTree(wr iter, table, row.Row!Instanc eId)
writer.WriteEnd Element()
Next
End Sub

Public Shared Sub Main()
Dim table As DataTable = CreateTable()
WriteDataSet(ta ble)
WriteXml(table)
End Sub

Generally I would use the WriteDataSet method rather then "rolling my own"
(WriteXml & WriteXmlTree). However "rolling my own" does provide extra
flexibilty...

Hope this helps
Jay

"RJN" <rj*@yahoo.co m> wrote in message
news:uJ******** ******@TK2MSFTN GP15.phx.gbl...
| Hi
|
| I need help in writing a recursive function. My table structure is as
| below.
|
| InstanceId LevelId ParentId
| 100 1 null
| 101 2 100
| 102 3 101
| 103 4 102
| 104 5 103
| 105 5 104
| 106 5 104
|
| From the above example, 100 is the root node which has a child 101, 101
| has a child 102 and so on. Given a instanceid I want to get all the
| child below that having levelid = 5. So if I give InstanceId=100, then I
| should get a list of 104, 105, 106. If I pass the instance id 104, then
| I should get 105 and 106. How I can I write a recursive function for
| this?
|
| Also I want to construct the xml tree structure. So passing in Instance
| Id, I should get the immediate child below that and so on. If instance
| id is 100, then there should be one leaf node 101 which will have
| another leaf node 102 and so on. Can anyone help me?
|
| Thanks
|
| rjn
|
|
|
| *** Sent via Developersdex http://www.developersdex.com ***
Nov 21 '05 #2
RJN
Hi Jay

Thanks for your reply. That was a great piece of code. But I've one
issue here. I need to fetch the data from database first. In the example
you have assumed that you already have the complete data in the data
table including all the child. But I need to fetch the complete data
from database given a parentid and drill down till the leaf nodes. Once
I have the complete data in my data table, then I can go ahead with your
suggestion.

Regards

rjn

*** Sent via Developersdex http://www.developersdex.com ***
Nov 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
10968
by: jalkadir | last post by:
Let's say that I have this class: class Parent{ private: char* str; public: const char* getStr(){return str;} }; And then I create a child class class Child{ private: std::string str; public: std::string& getStr(){return str;}
2
2907
by: Steven Burn | last post by:
..:: The Specs: MS Access 2000 (host charges extra for SQL/MySQL) MS Windows Server 2003 (prod) / MS XP SP1 (dev) ..:: The setup: The database has been setup with two tables; tblDownloads
20
18849
by: Gary Manigian | last post by:
I have 2 tables, one-to-many, that contain bills of material(BOMs): tblBOM: lngBOMID (PK) strAssemblyPartNo strDescription tblBOMDetail: lngBOMDetailID (PK) lngBOMID (FK)
14
3473
by: Fabian Steiner | last post by:
Hello! I have got a Python "Device" Object which has got a attribute (list) called children which my contain several other "Device" objects. I implemented it this way in order to achieve a kind of parent/child relationship. Now I would like to get all children of a given "Device" object and thought that it would be the best way to use recursive function.
2
1442
by: hardieca | last post by:
Hi, I'm building a CMS and I'm banging my head against the wall over one part of the user interface. I have a Section entity which maybe have 0 or 1 parent Sections. So, as an example, I could have a "Media" section which is the parent to a "New Release" section which is a parent to a "Recent Releases" section. I need to build a control that expresses the recursive relationship of each section to its parent, but it needs to be
9
2628
by: pereges | last post by:
Hello I need some ideas for designing a recursive function for my ray tracing program. The idea behind ray tracing is to follow the electromagnetic rays from the source, as they hit the object.The object is triangulated. The rays can undergo multiple reflections, diffractions etc of the same object i.e. a ray hits a surface of the object, undergoes reflection resulting in a reflected ray which can again hit a surface, corner or edge...
8
8303
by: Pivot_Tables | last post by:
Hi, I have created a recursive SQL Query in DB2 and it works fine until some point in the tree where the data gets into infinite loop. Below are some sample data from my relationship table. Relationship Table PARENT FIELD CHILD FIELD AAA BBB AAA CCC
0
1935
by: Pivot_Tables | last post by:
Please follow the below link as this post is continuation from the below post. http://groups.google.com/group/comp.databases.ibm-db2/browse_thread/thread/1589589ccf38eb0a Hi Guys, I got into another issue with this. I want to know if I can break the repeatation of the same parent child nodes in some other path. Here is
31
6657
by: matthewslyman | last post by:
I have an unusual design and some very unusual issues with my code... I have forced Access to cooperate on everything except one issue - record deletion. My form design involves a recursively nested form. In other words, the form, m_settings_menueditor_recursive has a single subform; m_settings_menueditor_recursive (both are viewed as datasheets - so the form is its own subdatasheet.) The Form_Open event modifies the form's recordset so...
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7362
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4177
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4343
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2760
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1984
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.