Getting the relational table data into XML recursively

Posted by Tom on Programmers See other posts from Programmers or by Tom
Published on 2013-10-28T15:10:14Z Indexed on 2013/10/28 16:14 UTC
Read the original article Hit count: 284

Filed under:
|
|

I have levels of tables (Level1, Level2, Level3, ...) For simplicity, we'll say I have 3 levels.

The rows in the higher level tables are parents of lower level table rows. The relationship does not skip levels however. E.g. Row1Level1 is parent of Row3Level2, Row2Level2 is parent of Row4Level3. Level(n-1)'s parent is always be in Level(n).

Given these tables with data, I need to come up with a recursive function that generates an XML file to represent the relationship and the data. E.g.

<data>
  <level levelid = 1 rowid=1>
    <level levelid = 2 rowid=3 />
  </level>
  <level levelid = 2 rowid=2>
    <level levelid = 3 rowid=4 />
  </level>
</data>  

I would like help with coming up with a pseudo-code for this setup. This is what I have so far:

XElement GetXMLData(Table table, string identifier, XElement data)
{
  XElement xmlData = data;

  if (table != null)
  {
    foreach (row in the table)
    {
       // Get subordinate table
       Table subordinateTable = GetSubordinateTable(table);

       // Get the XML Data for the children of current row
       xmlData += GetXMLData(subordinateTable, row.Identifier, xmlData);

    }
  }
  return xmlData;
}

© Programmers or respective owner

Related posts about c#

Related posts about recursion