2012-12-03 13 views
7

Ho un set di dati che ho creato utilizzando la ricorsione in SQL,Creare XML da un set di dati gerarchica in C#

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 

Ora voglio generare un XML che dovrebbe assomigliare a questo: -

<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> 

Voglio creare un XML gerarchico utilizzando la relazione padre e figlio da un set di dati.

+2

Guardare in espressioni di tabella comuni. http://msdn.microsoft.com/en-us/library/ms186243(v=sql.105).aspx – BenCr

+1

Se si utilizzano le stored procedure di SQL Server, è possibile restituire XML direttamente dalla procedura utilizzando FOR XML EXPLICIT (http://msdn.microsoft.com/en-us/library/ms189068.aspx – bUKaneer

+0

public class Person {Lista persone {get; set}} –

risposta

1

penso che si potrebbe utilizzare seguente frammento di codice:

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 

    } 
1

Penso che possa essere fatto con ricorsiva LINQ, ma ho ancora bisogno di capire come scrivere nel modo giusto, ecco una soluzione con metodo ricorsivo:

In primo luogo, si dichiara il metodo (che ho fatto ricerca per Name, ma si può anche farlo con Id):

public static IEnumerable<XElement> BuildXML(string Parent, DataTable dt) 
{ 
    string filter = string.Format("[Parent] = '{0}'", Parent); 
    return from x in dt.Select(filter) 
      select new XElement("Person", 
         new XAttribute("Name", x["Child"]), 
         new XAttribute("User_Id", x["Reporting_To_UserId"]), 
         BuildXML(x["Child"].ToString(), dt) 
        ); 
} 

Poi, si chiamano con il vostro elemento padre (ho aggiunto una riga sopra, tuttavia interrogazione sarà più complicato):

var dt = new DataTable(); 
dt.Columns.AddRange(new[] { 
    new DataColumn("Parent"), 
    new DataColumn("UserId"), 
    new DataColumn("Child"), 
    new DataColumn("Reporting_To_UserId"), 
    new DataColumn("Depth"), 
    new DataColumn("id") 
}); 
dt.Rows.Add(new object[] { "", 0, "Aditya", 13, 0, 12 }); 
dt.Rows.Add(new object[] {"Aditya", 13, "Abhishek", 4, 0, 13}); 
dt.Rows.Add(new object[] { "Abhishek", 4, "Saurabh", 6, 1, 16 }); 
dt.Rows.Add(new object[] { "Abhishek", 13, "Mohinder", 8, 1, 17 }); 
dt.Rows.Add(new object[] { "Mohinder", 8, "Mohammad", 14, 2, 18 }); 
dt.Rows.Add(new object[] { "Saurabh", 6, "Rahul", 1, 2, 11 }); 
dt.Rows.Add(new object[] { "Saurabh", 6, "Amitesh", 5, 2, 12 }); 

var result = BuildXML("", dt); 

Ora avete IEnumerable<XElement>, per trasformarlo in corda, si può fare di seguito:

var xml = result. 
      Select(e => e.ToString()). 
      Aggregate((current, next) => current + next); 
0

È possibile creare DataRelation su nel set di dati , Per esempio

DataRelation relation = new DataRelation("ParentChild", 
     ds.Tables["UserInfo"].Columns["MenuID"], 
     ds.Tables["UserInfo"].Columns["ParentID"], true); 
**relation.Nested = true;** 
ds.Relations.Add(relation); // 

L'attribuzione "Nidificata" è molto importante!

Makeyuan

Problemi correlati