using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
public partial class Default_aspx
{
void Page_Load(object sender, EventArgs e)
{
string xmlstr = "<?xml version=\"1.0\"?><root><Note NodeName=\"的1\"><Note NodeName=\"的2\"><Note NodeName=\"的3\" /><Note NodeName=\"的4\" /></Note><Note NodeName=\"的5\" /></Note><Note NodeName=\"的6\"><Note NodeName=\"的7\"><Note NodeName=\"的8\" /><Note NodeName=\"的9\" /></Note><Note NodeName=\"的10\" /></Note></root>";
IterateXml(xmlstr);
}
/*
<?xml version=\"1.0\"?><root><Note NodeName=\"的1\"><Note NodeName=\"的2\"><Note NodeName=\"的3\" /><Note NodeName=\"的4\" /></Note><Note NodeName=\"的5\" /></Note><Note NodeName=\"的6\"><Note NodeName=\"的7\"><Note NodeName=\"的8\" /><Note NodeName=\"的9\" /></Note><Note NodeName=\"的10\" /></Note></root>"
*/
private void IterateXml(string xmlstr)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlstr);
XmlNode worknode;
TreeNode rootnode;
for (int i = 0; i < xmldoc.DocumentElement.ChildNodes.Count; i++)
{
worknode = xmldoc.DocumentElement.ChildNodes[i];
if (worknode.ChildNodes.Count > 0)
rootnode = IterateChild(worknode);
else
rootnode = new TreeNode(worknode.Name);
this.TreeView1.Nodes.Add(rootnode);
}
}
private TreeNode IterateChild(XmlNode rootnode)
{
XmlNode worknode = rootnode;//当前遍历的节点
System.Web.UI.WebControls.TreeNode retnode = new TreeNode(worknode.Attributes["NodeName"].Value); ;//要返回的树节点
TreeNode newch;//中间树节点
if (worknode.ChildNodes.Count < 1)
{//没有子节点,生成一个树节点返回
newch = new TreeNode(worknode.Attributes["NodeName"].Value);
retnode = newch;
}
else //有子节点,调用递归
{
for (int i = 0; i < worknode.ChildNodes.Count; i++)
{
retnode.ChildNodes.Add(IterateChild(worknode.ChildNodes[i]));
}
}
return retnode;
}
}