---
title: " JavaScript解析XML文档成树菜单"
author: "dhj"
date: "2008-09-27T14:18:03Z"
tags: []
slug: "javascript-xml"
draft: false
lastmod: "2008-09-27T14:18:03Z"
id: 247485
url: "https://dang.iteye.com/blog/247485"
---

1.解析xml的BlueParseXML.js文件

001. /\**
002. * @description 解析并封装XML
003. * @author BluesLee
004. * @lastModif BluesLee
005. * @createDate 2007-10-13
006. * @modifDate 2007-10-15
007. * @version 1.0
008. \*/
009. //解析XML文件对象构造器
010. function  BlueParseXML(){
011. }
012. BlueParseXML.prototype.xml; //定义对象属性xml
013. BlueParseXML.prototype.loadFinish; //加载完成函数
014. BlueParseXML.prototype.nodeProperties= new  Array(); //节点属性数组
015. BlueParseXML.prototype.key= "key" ;
016. BlueParseXML.prototype.value= "value" ;
017. BlueParseXML.prototype.nodeList; //节点集合
018. BlueParseXML.prototype.rootName;
019. BlueParseXML.XML\_NULL=-1; //未加载xml，或加载失败
020. //加载xml文件
021. BlueParseXML.prototype.loadXML= function (url){
022. var  newXML;
023. var  obj= this ;
024. //如果它受支持，采用标准的2级DOM技术
025. if (document.implementation && document.implementation.createDocument){
026. //创建新的Document对象
027. //第一个参数是包含文档所使用的命名空间URI的字符串
028. //第二个参数是包含文档根元素名称的字符串
029. //第三个参数是要创建的文档类型（也称为doctype）。
030. //现在Firefox中并不提供针对文档类型的JavaScript支持，所以第三个参数总是为null。
031. newXML=document.implementation.createDocument( "" , "" , null );
032. //设置装载完毕时触发事件
033. newXML.onload= function (){
034. if (obj.loadFinish){
035. obj.loadFinish();
036. }
037. }
038. newXML.load(url);
039. } else { //IE浏览器创建Document对象
040. newXML= new  ActiveXObject( "Microsoft.XMLDOM" );
041. //设置onload
042. newXML.onreadystatechange= function (){
043. if (newXML.readyState==4){
044. if (obj.loadFinish){
045. obj.loadFinish();
046. }
047. }
048. }
049. newXML.load(url);
050. }
051. this .xml=newXML;
052. }
053. //解析遍历xml
054. BlueParseXML.prototype.parseXML= function (){
055. if (! this .xml){
056. alert( "XML未加载，请先加载XML文件！" );
057. return  parseXML.XML\_NULL;
058. }
059. var  rootNode= this .xml.documentElement;
060. this .rootName=rootNode.tagName;
061. this .nodeList= new  ChildNodeList();
062. this .level= this .iteratorNode( this .nodeList,rootNode,1);
063. return   this .level;
064. }
065. //遍历节点,将节点信息封装存入ChildNodeList中
066. BlueParseXML.prototype.iteratorNode= function (list,node,level){
067. if (!isNaN(level) && level&gt;0){
068. list.nodeLevel=level;
069. }
070. var  result=list.nodeLevel; //节点级别
071. var  flag= true ; //判断节点是否有子节点标记
072. for ( var  child=node.firstChild;child!= null ;child=child.nextSibling){
073. if (document.implementation && document.implementation.createDocument && !child.getAttribute){
074. continue ;
075. }
076. flag= false ; //有子节点
077. if (!list.nodeName || list.nodeName== "" ){
078. list.nodeName=child.tagName;
079. }
080. if (list.nodeName==child.tagName){
081. var  nodeInfo= new  NodeInfo();
082. nodeInfo.nodeLevel=list.nodeLevel; //设置节点级别
083. nodeInfo.nodeName=list.nodeName; //设置节点名称
084. nodeInfo.key=child.getAttribute( this .key); //设置节点属性
085. nodeInfo.value=child.getAttribute( this .value);
086. for ( var  index=0;index&lt; this .nodeProperties.length;index++){
087. nodeInfo\[ this .nodeProperties\[index]]=child.getAttribute( this .nodeProperties\[index]);
088. }
089. list.addElement(nodeInfo.key,nodeInfo); //把节点加入父节点的子节点集合
090. var  n= this .iteratorNode(nodeInfo.childNodeList,child,list.nodeLevel+1);
091. if (n&gt;result){ //如果子节点返回的节点级别大于改节点级别,设置返回节点级别为最大级别
092. result=n;
093. }
094. }
095. }
096. if (flag){ //当改节点没有子节点时返回的节点级别-1
097. result=result-1;
098. }
099. return  result;
100. }
101. //扩展String对象，增加trim方法去掉字符串前后空格
102. String.prototype.trim= function (){
103. return   this .replace(/^\\s\*/g, "" ).replace(/\\s\*$/g, "" );
104. }
105. /\**
106. * @description 自定义集合对象(利用对象属性键值对，类似Hashtable使用)
107. * @author BluesLee
108. * @lastModif BluesLee
109. * @createDate 2007-10-13
110. * @modifDate 2007-10-15
111. * @version 1.0
112. \*/
113. ChildNodeList.prototype.nodeLevel=1;
114. ChildNodeList.prototype.nodeName;
115. ChildNodeList.prototype.keyArray;
116. ChildNodeList.prototype.ELEMENT\_NULL=-1; //元素为空
117. ChildNodeList.prototype.ELEMENT\_EXIST=-2; //元素已经存在
118. ChildNodeList.prototype.ELEMENT\_NOT\_EXIST=-3; //元素不存在
119. ChildNodeList.prototype.INDEX\_OUT=-4 //数组下标越界
120. ChildNodeList.prototype.ERROR\_DELETE=-5 //删除元素出错
121. function  ChildNodeList(){
122. this .keyArray= new  Array();
123. }
124. //添加集合元素
125. ChildNodeList.prototype.addElement= function (key,element){
126. if (!key || !element){
127. return  ChildNodeList.ELEMENT\_NULL;
128. }
129. if ( this \[key]){
130. return  ChildNodeList.ELEMENT\_EXIST;
131. }
132. var  index= this .keyArray.length;
133. this .keyArray\[index]=key;
134. this \[key]=element;
135. return  index;
136. }
137. //根据下标删除集合元素
138. ChildNodeList.prototype.deleteElementByIndex= function (index){
139. if (index&gt;= this .keyArray.length){
140. return  ChildNodeList.INDEX\_OUT;
141. }
142. var  key= this .keyArray\[index];
143. for ( var  i=index;i&lt; this .keyArray.length;i++){
144. this .keyArray\[i]= this .keyArray\[i+1];
145. }
146. this .keyArray.length= this .keyArray.length-1;
147. delete   this \[key];
148. return  index;
149. }
150. //根据key删除集合元素
151. ChildNodeList.prototype.deleteElementByKey= function (key){
152. if (! this \[key]){
153. return  ChildNodeList.ELEMENT\_NOT\_EXIST;
154. }
155. for ( var  index=0;index&lt; this .keyArray.length;index++){
156. if ( this .keyArray\[index]==key){
157. return   this .deleteElementByIndex(index);
158. }
159. }
160. return  ChildNodeList.ERROR\_DELETE;
161. }
162. //根据key查找元素
163. ChildNodeList.prototype.getElementByKey= function (key){
164. return   this \[key];
165. }
166. //根据下标查找元素
167. ChildNodeList.prototype.getElementByIndex= function (index){
168. return   this .getElementByKey( this .keyArray\[index]);
169. }
170. //获取集合大小
171. ChildNodeList.prototype.size= function (){
172. return   this .keyArray.length;
173. }
174. /\**
175. * @description 节点信息封装对象
176. * @author BluesLee
177. * @lastModif BluesLee
178. * @createDate 2007-10-13
179. * @modifDate 2007-10-15
180. * @version 1.0
181. \*/
182. NodeInfo.prototype.nodeLevel;
183. NodeInfo.prototype.nodeName; //节点名称
184. NodeInfo.prototype.key; //节点名称,对应xml节点key属性
185. NodeInfo.prototype.value; //节点内容，对应xml节点value属性
186. NodeInfo.prototype.childNodeList; //子节点列表，用ChildNodeList对象封装
187. //构造器
188. function  NodeInfo(){
189. this .childNodeList= new  ChildNodeList();
190. }

2.BlueTree.js

001. /\**
002. * xml树对象 &lt;br&gt;
003. * Author：BluesLee &lt;br&gt;
004. * CreateDate：2008-7-9 &lt;br&gt;
005. * Modifier：BluesLee &lt;br&gt;
006. * ModifyDate：2008-7-9 &lt;br&gt;
007. * Version:1.1&lt;br&gt;
008. * Copyright(c)2008 深蓝工作室&lt;br&gt;
009. * All right reserved.&lt;br&gt;
010. \*
011. \*/
012. BlueTree.prototype.nodeArrayList; //节点总集合
013. BlueTree.prototype.isAddOnChangeEvent= false ;
014. BlueTree.prototype.SELECTLIST\_NULL=-1; //下拉对象数组为空
015. BlueTree.prototype.SELECTLIST\_TYPE\_NOT\_ARRAY=-2; //下拉对象数组不是数组对象
016. BlueTree.prototype.SELECTLIST\_EMPTY=-3; //下拉对象数组为空数组
017. BlueTree.prototype.SELECTLIST\_LENGTH\_OUT=-4; //下拉对象数组小于节点集合级别
018. BlueTree.prototype.NODELIST\_EMPTY=-5; //节点集合为空
019. BlueTree.prototype.EVENT\_NULL=-6; //事件源为空
020. //树属性
021. BlueTree.prototype.rootId;  //根节点ID
022. BlueTree.prototype.blueURL;  //点击节点超连接---isUseDataURL为false时有用
023. BlueTree.prototype.isUseDataURL;  //是否使用节点封装对象的节点超连接
024. BlueTree.prototype.rootName;  //根节点名称
025. BlueTree.prototype.imageURL;  //所有图片目录路径
026. BlueTree.prototype.rootImage;  //根节点图片
027. BlueTree.prototype.folderImg;  //有子节点关闭图片
028. BlueTree.prototype.folderOpenImg;  //有子节点展开图片
029. BlueTree.prototype.fileImg;  //无子节点图片
030. BlueTree.prototype.openImg;  //节点展开图片
031. BlueTree.prototype.closeImg;  //节点关闭图片
032. BlueTree.prototype.elementLineImg;  //带有节点的线图片
033. BlueTree.prototype.lineImg;  //无节点的线图片
034. BlueTree.prototype.endLineImg;  //最后一个节点线图片
035. BlueTree.prototype.endFolderOpenImg;  //最后一个有子节点展开图片
036. BlueTree.prototype.endFolderCloseImg;  //最后一个有子节点关闭图片
037. BlueTree.prototype.noneImg; //空白图片
038. BlueTree.prototype.isFolderURL;  //是否给有子节点的节点加超连接---isUseDataURL为false时有用
039. BlueTree.prototype.rootURL;  //根节点连接
040. BlueTree.prototype.target;  //所有连接的target属性
041. BlueTree.prototype.linkClass;  //超连接样式
042. BlueTree.prototype.styleClass;  //总样式
043. BlueTree.prototype.imgClass;  //图片样式
044. BlueTree.prototype.useDataImg;  //节点图片是否使用数据类图片，no为不使用，first为仅第一级目录使用，all全部使用
045. BlueTree.prototype.onMouseOver;  //鼠标经过每个节点时的样式
046. BlueTree.prototype.onMouseOut;  //鼠标离开每个节点时的样式
047. BlueTree.prototype.isCheckBox;  //是否带复选框控件
048. BlueTree.prototype.checkBoxName;  //复选框控件name
049. //构造器
050. function  BlueTree(nodeList){
051. if (nodeList){
052. this .nodeArrayList=nodeList;
053. } else {
054. this .nodeArrayList= new  ChildNodeList();
055. }
056. //初始化树属性
057. this .rootId =  "0" ;
058. this .blueURL =  "javascript:void(0);" ;
059. this .isUseDataURL =  "false" ;
060. this .rootName =  "根节点" ;
061. this .rootImage =  "rootImage.gif" ;
062. this .imageURL =  "images/" ;  //必须设置
063. this .folderImg =  "folder.gif" ;
064. this .folderOpenImg =  "folderOpen.gif" ;
065. this .fileImg =  "file.gif" ;
066. this .openImg =  "open.gif" ;
067. this .closeImg =  "close.gif" ;
068. this .elementLineImg =  "elementLine.gif" ;
069. this .lineImg =  "line.gif" ;
070. this .endLineImg =  "endLine.gif" ;
071. this .endFolderOpenImg =  "endFolderOpen.gif" ;
072. this .endFolderCloseImg =  "endFolderClose.gif" ;
073. this .noneImg =  "none.gif" ;
074. this .isFolderURL =  "true" ;
075. this .rootURL =  "javascript:void(0);" ;
076. this .target =  "\_blank" ;
077. this .linkClass =  "" ;
078. this .imgClass =  "" ;
079. this .styleClass =  "" ;
080. this .useDataImg =  "no" ;
081. this .onMouseOver =  "#CCCCCC" ;
082. this .onMouseOut =  "" ;
083. this .isCheckBox =  "true" ;
084. this .checkBoxName =  "checkbox" ;
085. }
086. /\**
087. * 根据节点集合构建树 &lt;br&gt;
088. * Author：李鹏 &lt;br&gt;
089. * CreateDate：2008-9-19 &lt;br&gt;
090. * Modifier：李鹏 &lt;br&gt;
091. * ModifyDate：2008-9-19 &lt;br&gt;
092. * Version:1.1&lt;br&gt;
093. \*
094. * @param parentObject,树所隶属父节点
095. * @param nodeList,即将展开节点集合
096. \*/
097. BlueTree.prototype.createTree= function (parentObject,nodeList){
098. parentObject.innerHTML= "" ;
099. if (!nodeList){
100. nodeList= this .nodeArrayList;
101. }
102. var  level=1;
103. var  tableNode=document.createElement( "table" );
104. tableNode.className= this \[ "styleClass" ];
105. tableNode.style.cssText= "border-collapse:collapse;border:0px solid;padding:0px;margin:0px;" ;
106. tableNode.border=0;
107. tableNode.cellPadding=0;
108. tableNode.cellSpacing=0;
109. //创建第N级节点
110. for ( var  i=0;i&lt;nodeList.size();i++){
111. var  nodeInfo=nodeList.getElementByIndex(i);
112. var  n\_id= "" ,name= "" ,url= "" ,ischild= "false" ,openimg= "" ,closeimg= "" ;
113. if (nodeInfo.key){
114. n\_id=nodeInfo.key;
115. }
116. if (nodeInfo.value){
117. name=nodeInfo.value;
118. }
119. if (nodeInfo.url){
120. url=nodeInfo.url;
121. }
122. if (nodeInfo.childNodeList.size()&gt;0){
123. ischild= "true" ;
124. }
125. if (nodeInfo.openimg){
126. openimg=nodeInfo.openimg;
127. }
128. if (nodeInfo.closeimg){
129. closeimg=nodeInfo.closeimg;
130. }
131. if (nodeInfo.nodeLevel && nodeInfo.nodeLevel!=level){
132. level=nodeInfo.nodeLevel;
133. }
134. //添加行
135. var  row=tableNode.insertRow(tableNode.rows.length);
136. addEvent(row, "mouseover" ,mouseOverNode);
137. addEvent(row, "mouseout" ,mouseOutNode);
138. //添加单元格
139. var  cell=row.insertCell(row.length);
140. cell.style.cssText= "white-space:nowrap;" ;
141. //根据节点级别加递进线图片
142. var  previousNodes;
143. try {
144. previousNodes=parentObject.parentNode.previousSibling.firstChild.childNodes;
145. for ( var  j=1;j&lt;level;j++){
146. var  img=document.createElement( "img" );
147. img.setAttribute( "align" , "absmiddle" );
148. /\**
149. * 判断是否是最后一级节点，如果是，递进线为空白
150. \*/
151. if (j+1==level){
152. if (previousNodes\[j-1].firstChild.src.indexOf( this \[ "endFolderOpenImg" ])&gt;0){
153. img.src= this \[ "imageURL" ]+ this \[ "noneImg" ];
154. } else {
155. img.src= this \[ "imageURL" ]+ this \[ "lineImg" ];
156. }
157. } else {
158. img.src=previousNodes\[j-1].src;
159. }
160. img.className= this \[ "imgClass" ];
161. cell.appendChild(img);
162. }
163. } catch (e){
164. }
165. //添加节点事件区域
166. var  eventArea=document.createElement( "span" );
167. eventArea.style.cssText= "cursor:pointer;" ;
168. //加节点展开关闭图片
169. var  imgOpenOrClose=document.createElement( "img" );
170. imgOpenOrClose.setAttribute( "align" , "absmiddle" );
171. imgOpenOrClose.className= this \[ "imgClass" ];
172. imgOpenOrClose.setAttribute( "id" , "sign\_img\_" +level+ "\_" +n\_id);
173. if ((i+1)!=nodeList.size()){
174. if (ischild && ischild.trim()== "true" ){
175. imgOpenOrClose.src= this \[ "imageURL" ]+ this \[ "closeImg" ];
176. } else {
177. imgOpenOrClose.src= this \[ "imageURL" ]+ this \[ "elementLineImg" ];
178. }
179. } else {
180. if (ischild && ischild.trim()== "true" ){
181. imgOpenOrClose.src= this \[ "imageURL" ]+ this \[ "endFolderCloseImg" ];
182. } else {
183. imgOpenOrClose.src= this \[ "imageURL" ]+ this \[ "endLineImg" ];
184. }
185. }
186. eventArea.appendChild(imgOpenOrClose);
187. //添加节点图片
188. var  imgNodeOpenOrClose=document.createElement( "img" );
189. imgNodeOpenOrClose.setAttribute( "align" , "absmiddle" );
190. imgNodeOpenOrClose.className= this \[ "imgClass" ];
191. imgNodeOpenOrClose.setAttribute( "id" , "node\_img\_" +level+ "\_" +n\_id);
192. if ( this \[ "useDataImg" ].toLowerCase()== "all" ){
193. imgNodeOpenOrClose.src= this \[ "imageURL" ]+openimg;
194. } else {
195. if (ischild && ischild.trim()== "true" ){
196. imgNodeOpenOrClose.src= this \[ "imageURL" ]+ this \[ "folderImg" ];
197. } else {
198. imgNodeOpenOrClose.src= this \[ "imageURL" ]+ this \[ "fileImg" ];
199. }
200. }
201. eventArea.appendChild(imgNodeOpenOrClose);
202. //节点事件参数
203. var  file\_image\_param= null ,node\_img\_open\_param= null ,node\_img\_colse\_param= null ;
204. if ( this \[ "useDataImg" ].toLowerCase()== "all" ){
205. file\_image\_param=openimg;
206. node\_img\_open\_param=openimg;
207. node\_img\_colse\_param=closeimg;
208. } else {
209. file\_image\_param= this \[ "fileImg" ];
210. node\_img\_open\_param= this \[ "folderOpenImg" ];
211. node\_img\_colse\_param= this \[ "folderImg" ];
212. }
213. var  img\_open\_param= null ,img\_close\_param= null ;
214. if ((i+1)!=nodeList.size().length){
215. img\_open\_param= this \[ "openImg" ];
216. &n