• 递归遍历XML生成树


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

  • 相关阅读:
    Requests库常用方法及其详解
    MacOS下搭建python环境
    Requests库与HTTP协议
    MacOS下安装Requests库及使用
    Swing State: Consistent Updates for Stateful and Programmable Data Planes
    Transparent Flow Migration for NFV
    2018软工团队选题报告
    Traffic Steering for Service Function Chaining
    2018年软工第二次结对作业
    【数字图像处理】Tencent视频团队讲座记录
  • 原文地址:https://www.cnblogs.com/toney/p/66178.html
Copyright © 2020-2023  润新知