将XML文件转换为easyui Tree结构json

前端之家收集整理的这篇文章主要介绍了将XML文件转换为easyui Tree结构json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
private void GetTreeCamera()
       {
           XmlDocument xmlDoc = new XmlDocument();
           xmlDoc.Load(HttpContext.Current.Server.MapPath("camera.xml"));
           StringBuilder result = new StringBuilder();
           StringBuilder sb = new StringBuilder();
           //获取当前XML文档的根 一级
           XmlNode oNode = xmlDoc.DocumentElement;
           if (!oNode.HasChildNodes)
               result.Append("[]");
           else
           {
               //获取根节点的所有子节点列表 
               XmlNodeList oList = oNode.ChildNodes;
               result.Append("[");
               foreach (XmlNode Node in oList)
               {
                   sb.Clear();
                   string r1 = getJsonByNode(Node,sb);
                   result.Append(r1);
               }
               result = result.Remove(result.Length - 1,1);
               result.Append("]");
           }
           WebHelper.HttpResponseJson(result.ToString());
       }
        /// <summary>
        /// 遍历结点,拼接json
        /// </summary>
        /// <param name="Node"></param>
        /// <param name="sb"></param>
        /// <returns></returns>
        private string getJsonByNode(XmlNode Node,StringBuilder sb)
        {
            if (!Node.HasChildNodes)
            {
                sb.Append("{\"id\":\"" + Node.Attributes["id"].Value + "\",\"text\":\"" + Node.Attributes["name"].Value.Trim() + "\",\"state\":\"open\"},");
            }
            else
            {
                sb.Append("{\"text\":\"" + Node.Attributes["name"].Value.Trim() + "\",\"children\":[");
                XmlNodeList oList2 = Node.ChildNodes;
                foreach (XmlNode Node2 in oList2)
                {
                    getJsonByNode(Node2,sb);
                }
                sb = sb.Remove(sb.Length - 1,1);
                sb.Append("]},");
            }
            return sb.ToString();
        }
原文链接:https://www.f2er.com/xml/300011.html

猜你在找的XML相关文章