循环写入xml for treeview

时间:2014-02-25 11:03:42

标签: c# asp.net xml wpf treeview

我从Web窗体应用程序中的SQL数据库中读取数据,并将其写入XML文件并使用TreeView控件显示它们。但问题是我只能从数据库中读取带有ParentID 0的树并使用TreeView显示它们。如何在TreeView上显示ParentID 1的子树?  从数据库中读取:

public DataTable GetMenu(int parentId)
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection("Data Source =(Local);Initial Catalog=Tajari;Integrated Security=True;"))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from TBLJobs where ParentId=@ParentId", con);
        cmd.Parameters.AddWithValue("@ParentId", parentId);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        con.Close();
        return dt;
    }
}

创建XML文件代码:

private void CreateNodes(int parentId)
{
    DataTable dt = GetMenu(0);
    foreach(DataRow dr in dt.Rows)
    {
        writer.WriteStartElement("Node");
        writer.WriteStartAttribute("Id");
        writer.WriteValue(dr["MenuId"].ToString());
        writer.WriteEndAttribute();

        writer.WriteStartAttribute("Name");
        writer.WriteValue(dr["MenuName"].ToString());
        writer.WriteEndAttribute();

        writer.WriteEndElement();
    }
}

使用XMLWriter写入XML文件

public void CreateMenu()
{
    using (writer = XmlWriter.Create(Server.MapPath("Temp\\Menu.XML")))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("Menu");
        CreateNodes(0);
        writer.WriteEndDocument();
    }
}

1 个答案:

答案 0 :(得分:0)

private void CreateNodes(int parentId)
{
    DataTable dt = GetMenu(0);
    foreach(DataRow dr in dt.Rows)
    {
        writer.WriteStartElement("Node");
        writer.WriteStartAttribute("Id");
        writer.WriteValue(dr["MenuId"].ToString());
        writer.WriteEndAttribute();

        writer.WriteStartAttribute("Name");
        writer.WriteValue(dr["MenuName"].ToString());
        writer.WriteEndAttribute();

        **CreateNodes(Convert.ToInt32(dr["MenuId"]));**
        writer.WriteEndElement();
    }
}