﻿/*
@class:		XPath
@author:	Kinglong(kinglong@gmail.com)
@version:	0.5
@link:		http://www.klstudio.com
@build:		20080122
@lib:		none

seXML(source)
     解析xml数据
     source为xml字符数据;
     返回值为xml的根节点;
XPath.loadXML(path)
     加载xml文件
     path为xml文件路径;
     返回值为xml的根节点
XPath.getChildren(node, name)
     获取node节点下所有name的子节点数组;
XPath.getChild(node, name)
     获取node节点下name的子节点;
XPath.selectNodes(node,path,child)
     获取node节点下的子节点数组;
     node为当前节点；
     path为节点路径；
     child为子节点名；
XPath.selectSingleNode(node,path)
     获取node节点下的子节点
     node为当前节点；
     path为节点路径；
XPath.getNodeValue(node)
     获取文本节点的值；
     
*/
XPath = {
	getIEXmlAX:function (){
		var i,activeXarr;
		var activeXarr = [			
			"MSXML4.DOMDocument",
			"MSXML3.DOMDocument",
			"MSXML2.DOMDocument",
			"MSXML.DOMDocument",
			"Microsoft.XmlDom"
						];	
		for(i=0; i<activeXarr.length; i++){
			try{
				var o = new ActiveXObject(activeXarr[i]);
				return o;
			}catch(e){}
		}
		return false;
	}
	,
	parseXML:function(source){
		try{
			var domParser = new DOMParser();
			var o = domParser.parseFromString(source,'text/xml');	
			return o.documentElement;
		}catch(e){
			try{
				var o = this.getIEXmlAX();
				o.loadXML(source);
				return o.documentElement;
			}catch(e){
				return null;
			}
		}
	}
	,
	loadXML:function(path){
		var xmlDoc=null;
		if (window.ActiveXObject){
			xmlDoc=this.getIEXmlAX();
		}else if (document.implementation && document.implementation.createDocument){
			xmlDoc=document.implementation.createDocument("","",null);
		}else{
			alert('Your browser cannot handle this script');
		}
		xmlDoc.async=false;
		xmlDoc.load(path);
		return xmlDoc;
	}
	,
	getChildren:function(node,name){
		var nodes = [];
		for(var i=0;i<node.childNodes.length;i++){
			if(node.childNodes[i].nodeName == name){
				nodes[nodes.length] = node.childNodes[i];
			}
		}
		return nodes;
	}
	,
	getChild:function(node,name){		
		for(var i=0;i<node.childNodes.length;i++){
			if(node.childNodes[i].nodeName == name){
				return node.childNodes[i];
			}
		}
		return null;
	}
	,
	selectNodes:function(node,path,child){
		var paths = path.split("/");
		for(var i=0;i<paths.length;i++){
			node = this.getChild(node,paths[i]);
			if(node == null){
				return [];
			}
		}
		return this.getChildren(node,child);		
	}
	,
	selectSingleNode:function(node,path){
		var paths = path.split("/");
		for(var i=0;i<paths.length;i++){
			node = this.getChild(node,paths[i]);
			if(node == null){
				return null;
			}
		}		
		return node;
	}
	,
	getNodeValue:function(node){
	    if (node.hasChildNodes() == true)
		    return node.firstChild.nodeValue;
        else
            return "";
	}
};
