C#递归生成HTML树
public StringBuilder str = new StringBuilder(); //定义一个字符串
private void get_navigation_childs(List<TableClass> oldData, string parent_id) { List<TableClass> dr = oldData.Where(x => x.PCode == parent_id).OrderBy(x => x.Kid).ToList(); //Code代表节点信息,PCode代表父级节点信息,PMMC代表节点名称 bool isWrite = false; //是否输出开始标签 for (int i = 0; i < dr.Count(); i++) { //如果是*导航 if (parent_id == "") { str.Append("<ul>"); str.Append("<li class='parent_li' >"); str.Append("<span title='Collapse this branch'>"); str.Append("<i class='icon-folder-open'></i>" + dr[i].PMMC + "</span> "); //str.Append("<a href='RoleListEdit.aspx?id=" + dr[i].ID + "&type=Edit'>编辑</a> \n"); //str.Append("<a data='RoleListList.aspx?id=" + dr[i].ID + "&type=Del' onclick='del(this)' >删除</a> \n"); //调用自身迭代 this.get_navigation_childs(oldData, dr[i].Code); str.Append("</ul>"); } else //下级导航 { if (!isWrite) { isWrite = true; str.Append("<ul>"); } str.Append("<li>"); str.Append(" <span><i class='icon-leaf'></i>" + dr[i].PMMC + "</span>"); //str.Append("<a href='RoleListEdit.aspx?id=" + dr[i].ID + "&type=Edit'>编辑</a> \n"); //str.Append("<a data='RoleListList.aspx?id=" + dr[i].ID + "&type=Del' onclick='del(this)' >删除</a> \n"); //调用自身迭代 this.get_navigation_childs(oldData, dr[i].Code); str.Append("</li>"); if (i == (dr.Count() - 1)) { str.Append("</ul>"); } } } }
C#递归生成XML树
public void TestBuild(string Path)
{
DataTable dt = InitTable();
XmlElement xe = xd.CreateElement("Datas");
xd.AppendChild(xe);
//执行递归,添加XML节点
BTest(dt, xe);
XmlDocument doc = new XmlDocument();
doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + xd.OuterXml.ToString().Replace("/>", "></Item>"));
doc.Save(Path);
}
/// <summary> /// 递归添加XML节点 /// </summary> /// <param name="dt">数据源</param> /// <param name="node">当前节点</param> public void BTest(DataTable dt, XmlElement node) { XmlElement tmp; var list = from r in dt.AsEnumerable() select r; if (node != null && node.Attributes["Code"] != null) { list = from r in dt.AsEnumerable() where r["PCode"].ToString().Equals(node.Attributes["Code"].Value) select r; } foreach (DataRow row in list) { if (!usedElement.Contains(row["Code"].ToString())) { usedElement.Add(row["Code"].ToString()); tmp = xd.CreateElement("Item"); var a = tmp.NodeType; tmp.SetAttribute("Code", row["Code"].ToString()); tmp.SetAttribute("PCode", row["PCode"].ToString()); //tmp.InnerText = row["PMMC"].ToString(); node.AppendChild(tmp); BTest(dt, tmp); } } }