Posted on 2007-08-14 14:29
G_G 阅读(1193)
评论(1) 编辑 收藏 所属分类:
xml Related
问题:
IE,FF用 xpath 在javascript动态解读
解决: 自定义jsXpath 类
js.js
//关键是 jsXpath 类
//使用是 new 并 给属性 domx 值 DOMXml
//var nodes = obj.getPathNodes( xpath ); 就是 xpath语句如://beans/bean
//再 var node = obj.next( nodes )
//node 可以使用了
var dom = null ;
var jp = new jsXpath();
function load(ul){
new Ajax.Request(
ul,
{
method: 'get',
onComplete: action
});
}
function action(req){
var path = " /beans/bean[string-length(@xid)<3] ";
dom = req.responseXML ;
jp.domx = dom ;
var list = jp.getPathNodes(path) ;
createSelect(jp,list, document.getElementById('ii') );
//建 select ii
}
function jsXpath(){
this.nexti = 0 ;
this.domx = null ;
this.getPathNodes = function(path){
var val =null ;
if( navigator.appName.indexOf('Microsoft')== -1 ){
val = document.evaluate(path,this.domx ,null,XPathResult.ANY_TYPE,null ) ;
}else{
this.domx.setProperty("SelectionLanguage","XPath");
val = this.domx.documentElement.selectNodes( path ) ;
}
return val ;
}
this.next = function(domp,ii){
if( navigator.appName.indexOf('Microsoft')== -1 ){
return domp.iterateNext() ;
}else{
if(ii!=null) this.nexti = ii ;
return domp[this.nexti++];
}
}
}
function createSelect(xpath,doms,sele){
try{
var item=xpath.next(doms);
while(item){
var opt =document.createElement('option');
var text=document.createTextNode( item.firstChild.nodeValue );
opt.appendChild(text);
opt.setAttribute("value",item.getAttribute('xid') );
sele.appendChild(opt);
item = xpath.next(doms);
}
}catch(e){dump(e);}
}
//建 select jj 与 select ii的 selectedIndex 有关
function duSel(){
var sele = document.getElementById('jj');
var sdom = document.getElementById('ii');
var num = sele.getElementsByTagName('option').length-1;
for(var i=num; i>0 ; i--)
sele.remove(1);
var skey = sdom.options[ sdom.selectedIndex ].value
var path = "/beans/bean[ starts-with( @xid , '"+skey+"') and string-length(@xid)>3 ]";
var jpp = new jsXpath();
jpp.domx = dom ;
var lj = jpp.getPathNodes(path);
createSelect(jpp,lj, document.getElementById('jj') );
}
xml.xml
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<beans>
<bean xid='01' >北京局</bean>
<bean xid='0101'>ftd</bean>
<bean xid='0102'>tsd</bean>
<bean xid='02'>沈阳局</bean>
<bean xid='0202'>sy1</bean>
<bean xid='0203'>sy2</bean>
<bean xid='0204'>sy3</bean>
</beans>
xpath.html
//级连的 下拉框出来了<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script language='JavaScript' src="js/js.js"></script>
<script language="JavaScript" src="lib/prototype/prototype.js"></script>
<script language='JavaScript' src='js/xpath.js'></script>
</head>
<body onload='load( "./xml/xml.xml" )'>
<select id="ii" onchange='duSel();'>
<option value="" >--段选择--</option>
</select>
<select id="jj">
<option value="" >--车间选择--</option>
</select>
</body>
</html>
心得: xpath 是好东西 好东西啊