c# - 在 C# 中从分层数据集创建 XML

标签 c# asp.net xml xml-parsing dataset

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

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

现在我想生成一个应该如下所示的 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>

我想使用数据集中的父子关系创建分层 XML。

最佳答案

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

 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

    }

关于c# - 在 C# 中从分层数据集创建 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686729/

相关文章:

mysql - 在Flash中更新变量后重新请求xml数据

ruby - 谁能帮我使用 Ruby 抓取亚马逊产品 API?

asp.net - 哪一种最适合 3 层架构; Linq to SQL 还是 Nhibernate?

asp.net - 返回 XML 作为 HTTP 响应

c# - 处理大量文件

c# - 如何在C#中实现类似python风格的多个返回值

asp.net - 测试对象实例返回 "Conversion from string "“输入 'Boolean' 无效。”

xml - 我可以在 VS 2010 HTML 片段中包含 CDATA 部分吗?

c# - Rabbitmq 消息未出现在 c# 的队列中

c# - 使用 Razor 按表中的日期对模型元素进行分组