一个快捷操作XML数据库的Javascript接口对象,包含select、count、tables、fields等方法,能够像操作mysql等其它数据库一样操作XML数据库。
if(document.implementation.hasFeature("XPath","3.0")){ //浏览器bug修复
XMLDocument.prototype.selectNodes=function(cXPathString,xNode){
if(!xNode){xNode=this;}
var oNSResolver=this.createNSResolver(this.documentElement);
var aItems=this.evaluate(cXPathString, xNode, oNSResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var aResult=[];
for(var i=0;i< aItems.snapshotLength;i++){
aResult[i]=aItems.snapshotItem(i);
}
return aResult;
}
Element.prototype.selectNodes=function(cXPathString){
if(this.ownerDocument.selectNodes){
return this.ownerDocument.selectNodes(cXPathString,this);
}else{throw "For XML Elements Only";}
}
}
/*
jQuery版本要求:1.7.2
XML数据库查询类,实现的方法
load(pt,async):
loadFromText(xStr):
select(tb,data,where,order,limit,group);
count(tb,where);
tables();
fields(tb);
*/
function xml_db(pt,async){
var _root=this,async=typeof(async)!="undefined"?async:true;
_root.dbObj=null;/*数据库对象数组*/
_root.status=false;/*数据库对象数组*/
_root.dbpath=typeof(pt)!="undefined"?pt:false;/*数据库路径*/
_root.ifAutoPara=true;
var autoPara=function(para,oriParas){/*自动附加参数*/
if(para.length >2){
for(var i=2;i< para.length;i++){
if(para[i].match(/^\s*where/i)){oriParas['where']=para[i];}
if(para[i].match(/^\s*order/i)){oriParas['order']=para[i];}
if(para[i].match(/^\s*limit/i)){oriParas['limit']=para[i];}
if(para[i].match(/^\s*group/i)){oriParas['group']=para[i];}
}
}
},
WOLG=function(str,kw,oriParas){/*附加参数*/
if(typeof(str)!="undefined"){
var reg=new RegExp("^"+kw+"\\s*","ig"),ky=kw.replace(/\s+\w+/gi,"");
str=str.replace(reg,"");
oriParas[ky]=kw+" "+str;
}
},
decode=function(string,quote_style){/*解码*/
var optTemp=0,i=0,noquotes=false;
if(typeof quote_style === 'undefined'){quote_style=2;}
string=string.toString().replace(/</g, '<').replace(/>/g, '>');
var OPTS={'ENT_NOQUOTES': 0,'ENT_HTML_QUOTE_SINGLE': 1,'ENT_HTML_QUOTE_DOUBLE':2,'ENT_COMPAT':2,'ENT_QUOTES':3,'ENT_IGNORE':4};
if(quote_style===0){noquotes=true;}
if(typeof quote_style !== 'number'){
quote_style=[].concat(quote_style);
for(i=0; i < quote_style.length; i++){
if(OPTS[quote_style[i]] === 0){
noquotes=true;
}else if(OPTS[quote_style[i]]){
optTemp=optTemp | OPTS[quote_style[i]];
}
}
quote_style=optTemp;
}
if(quote_style & OPTS.ENT_HTML_QUOTE_SINGLE){
string=string.replace(/�*39;/g, "'");
string=string.replace(/'|�*27;/g, "'");
}
if(!noquotes){string=string.replace(/"/g, '"');}
string=string.replace(/&/g, '&');
return string;
},
xQuery=function(str,node){
return typeof(node)!="undefined"? node.selectNodes(str):_root.dbObj.selectNodes(str);
};
_root.load=function(pt,async){
var pt=typeof(pt)!="undefined"?pt:_root.dbpath,
async=typeof(async)!="undefined"?async:true;
jQuery.ajax({
'type': "GET",
'url':pt,
'dataType':'text',
'cache': false,
'async': async,
'success': function(dt){
var root=_root.loadFromText(dt.replace(/[\r\n]+/gmi,"").replace(/<!--.*?-->/gi,"").replace(/>\s+/gi,">"));
if(root){
_root.dbObj=root.documentElement;
}
}
});
};
_root.loadFromText=function (xStr){
try{
if(window.DOMParser){
parser=new DOMParser();
txmlDoc=parser.parseFromString(xStr,"text/xml");
}else{
txmlDoc=new ActiveXObject("Microsoft.XMLDOM");
txmlDoc.async="false";
txmlDoc.loadXML(xStr);
}
_root.status=txmlDoc.documentElement?true:false;
return _root.status?txmlDoc:false;
}catch(e){
_root.status=false;
return false;
}
};
_root.query=function(){
};
_root.select=function(tb,data,where,order,limit,group){
if(!_root.status){return false;}
var addtion={},data=typeof(data)=="undefined"?"*":data;
if(!_root.ifAutoPara){ /*自动附加参数*/
autoPara(arguments,addtion);
}else{
WOLG(where,"where",addtion);
WOLG(order,"order by",addtion);
WOLG(limit,"limit",addtion);
WOLG(group,"group by",addtion);
}
if(typeof(addtion['where'])=="undefined"){
addtion['where']="where `id`>=0";
}
addtion['where']=addtion['where'].replace(/&&/gi," and ").replace(/\|\|/gi," or ");
addtion['where']=addtion['where'].replace(/^\s*where\s*/gi,"");
var fdArr=_root.fields(tb),sFdArr,reg=new RegExp(),oArr,rArr=[];/*相关变量定义*/
if(data!="*"){
sFdArr=jQuery.grep(
jQuery.type(data)=="array"?data:data.split(/\s*,\s*/gi),function(n,i){
return jQuery.inArray(n,fdArr)!=-1;
});
if(!sFdArr.length){return false;}
if(jQuery.inArray("id",sFdArr)==-1){sFdArr.push("id");}
}
jQuery.each(fdArr,function(i,n){
reg.compile('`'+n+'`',"gi");
addtion['where']=addtion['where'].replace(reg,"v"+i);
});
oArr=xQuery("//root/"+tb+"/it["+addtion['where']+"]");
jQuery.each(oArr,function(i,n){
var orArr={};
jQuery.each(n.childNodes,function(dx,cNode){
var curVL=jQuery(cNode).text();
curVL=curVL.match(/^\d+$/,"gi")?parseInt(curVL):(curVL.match(/^\d+\.\d+$/,"gi")?parseFloat(curVL):decode(curVL));
if(data=="*"){
orArr[fdArr[dx]]=curVL;
}else if(jQuery.inArray(fdArr[dx],sFdArr)!=-1){
orArr[fdArr[dx]]=curVL;
}
});
rArr.push(orArr);
});
if(typeof(addtion['order'])!="undefined"){
if(addtion['order'].match(/^\s*order\s+by\s+`?(\w+)`?\s+(asc|desc)\s*$/gi)){
var orders=[];
orders[0]=(jQuery.inArray(RegExp.$1.toString(),fdArr)!=-1)?RegExp.$1.toString():"id";
orders[1]=(jQuery.inArray(RegExp.$2.toString(),["desc","asc"])!=-1)?RegExp.$2.toString():"desc";
rArr.sort(function(a,b){
var ca=0,cb=0;
if(a[orders[0]].toString().match(/^\d+$/gi)&&b[orders[0]].toString().match(/^\d+$/gi)){
ca=parseInt(a[orders[0]]);cb=parseInt(b[orders[0]]);
}else if(a[orders[0]].toString().match(/^\d+\.\d+$/gi)&&b[orders[0]].toString().match(/^\d+\.\d+$/gi)){
ca=parseFloat(a[orders[0]]);cb=parseFloat(b[orders[0]]);
}else{
ca=a[orders[0]];cb=b[orders[0]];
}
if(ca==cb)return 0;
if(orders[1].toLowerCase()=='asc'){
return (ca > cb)? 1 : -1;
}else{
return (ca < cb)? 1 : -1;
}
});
}
};
if(typeof(addtion['limit'])!="undefined"){
if(addtion['limit'].match(/^\s*limit\s+(\d+)\s*,\s*(\d+)\s*$/gi)){
var itemsnum=rArr.length,snum=parseInt(RegExp.$1),lenum=parseInt(RegExp.$2);
snum=(snum < 0) ? 0:(snum < itemsnum ? snum : (itemsnum-1));
rArr2=[];
for(var i=0;i< itemsnum;i++){
if(i >= snum && i <= (snum+lenum-1)){
rArr2.push(rArr[i]);
}
}
return rArr2;
}
}
return rArr;
};
_root.count=function(tb,where){
if(!_root.status){return false;}
var fdArr=_root.fields(tb),reg=new RegExp(),addtion={};
WOLG(where,"where",addtion);
if(typeof(addtion['where'])=="undefined"){
addtion['where']="where `id`>=0";
}
addtion['where']=addtion['where'].replace(/&&/gi," and ").replace(/\|\|/gi," or ");
addtion['where']=addtion['where'].replace(/^\s*where\s*/gi,"");
jQuery.each(fdArr,function(i,n){
reg.compile('`'+n+'`',"gi");
addtion['where']=addtion['where'].replace(reg,"v"+i);
});
return xQuery("//root/"+tb+"/it["+addtion['where']+"]").length;
};
_root.fields=function(tb){
if(!_root.status){return false;}
var tbInfo=xQuery('//root/'+tb);
return tbInfo.length >0 ? tbInfo[0].getAttribute("fd").split("|"):[];
};
_root.tables=function(){
if(!_root.status){return false;}
var tbArr=[];
jQuery.each(xQuery('//root')[0].childNodes,function(dx,n){
tbArr.push(n.tagName);
});
return tbArr;
}
if(_root.dbpath!==false){
_root.load(_root.dbpath,async);
}
}
XML数据库文件格式(文件名为:db.xml):
<?xml version="1.0" encoding="UTF-8"?>
<root>
<menu fd="id|name|mtype|level|year|major">
<it>
<v0>1</v0>
<v1>云南财经大学</v1>
<v2></v2>
<v3>专升本</v3>
<v4>3年</v4>
<v5>工商管理</v5>
</it>
<it>
<v0>2</v0>
<v1>云南财经大学</v1>
<v2></v2>
<v3>专升本</v3>
<v4>3年</v4>
<v5>会计学</v5>
</it>
<it>
<v0>3</v0>
<v1>云南财经大学</v1>
<v2></v2>
<v3>专升本</v3>
<v4>3年</v4>
<v5>金融学</v5>
</it>
<it>
<v0>4</v0>
<v1>云南财经大学</v1>
<v2></v2>
<v3>高升专</v3>
<v4>3年</v4>
<v5>法律事务</v5>
</it>
</menu>
</root>
使用方法介绍:
var dbObj=new xml_db("db.xml",false);
var data=dbObj.select("menu","id,name,major","where `major`!='金融学'","limit 0,2","order by `id` desc");
for(var i=0;i< data.length;i++){
document.write(i+"->id:"+data[i]['id']+" name:"+data[i]['name']+" major:"+data[i]['major']+"<br/>");
}
输出:
0->id:1 name:云南财经大学 major:工商管理
1->id:2 name:云南财经大学 major:会计学
其它方法说明:
tables():返回所有表的数组;
fields(tb):返回表名为tb的所有字段名;
count(tb,where):返回表tb中符合where条件的记录数量