从C#中的分层数据集创建XML

Rah*_*hul 7 c# xml asp.net dataset xml-parsing

我有一个数据集,我使用SQL中的Recursion创建,

Parent        UserId   Child     Reporting_To_UserId   Depth        id
Aditya         13     Abhishek     4                   0            13
Abhishek       4      Saurabh      6                   1            16
Abhishek       4      Mohinder     8                   1            17
Mohinder       8      Mohammad     14                  2            18
Saurabh        6      Rahul        1                   2            11
Saurabh        6      Amitesh      5                   2            12
Run Code Online (Sandbox Code Playgroud)

现在我想生成一个看起来像这样的XML: -

 <Person name="Aditya" User_Id="13">

    <Person name="Abhishek" User_Id="4">

           <Person name="Mohinder" User_id="8">
               <Person name="Mohammad" User_id="14"/>
           </Person>         

           <Person name="Saurabh" User_Id="6">
              <Person name="Rahul" User_Id="1"/>
              <Person name="Amitesh" User_Id="5"/>
           </Person>

     </Person>

 </Person>
Run Code Online (Sandbox Code Playgroud)

我想使用数据集中的父和子关系创建一个Hierarchical XML.

Pra*_*tik 1

我认为您可以利用以下代码:

 protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        string connStr = @"Data Source=MY-PC\SQLExpress;Initial Catalog=DataDB;User Id=ME;Password=YourPassword;Trusted_Connection=True;";
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            string sql = "Select MenuID, Text,Description, ParentID from UserInfo";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            da.Fill(ds);
            da.Dispose();
        }
        ds.DataSetName = "UserInfos"; //You can start directly from here as you have the dataset just mantain Parent and Child ID Proper
        ds.Tables[0].TableName = "UserInfo";
        DataRelation relation = new DataRelation("ParentChild",
         ds.Tables["UserInfo"].Columns["MenuID"],
         ds.Tables["UserInfo"].Columns["ParentID"], true);

        relation.Nested = true;
        ds.Relations.Add(relation);  //XmlDataSource1 is any source of xml you can have this in file also
        XmlDataSource1.Data = ds.GetXml(); //Here Dataset will automatically generate XML for u based on relations added

    }
Run Code Online (Sandbox Code Playgroud)