天天看点

unXpah反转xpath路径表达式为html结构(一)

反转xpath路径表达式为html结构(一):单层标签反转解析;

var unXpath = function (X){

var A = X.split( / \]\[|\[|\] / ); // 属性分组处理

A[ 0 ] = A[ 0 ].replace( / (#)(\w+(?=(\s|\.|\[|$))) / , ' id="$2" ' ); // 转换ID

A[ 0 ] = A[ 0 ].replace( / (\.)(\S+(?=($))) / , ' class="$2" ' ).replace( / \. / g, " " ); // 转换class

var T = ' <{a}></{b}> ' .replace( / {a} / ,A.join( " " )).replace( / {b} / ,A[ 0 ].split( " " )[ 0 ]); // 组合生成html完整结构

return T.replace( / (\s>|\s{2}\ / > ) / ,">").replace( / ( >< \ / )(input|img|br)(>) / , " /> " ); // 单闭合标签处理

}

alert(unXpath( ' div#I.me.she.he[id="info"][title="小web"] ' ));

// 返回<div id="info" class="me she he" title="小web"></div>

alert(unXpath( ' input#Ta.she[type="text"][title="小web"] ' ));

// 返回<input type="text" id="Ta" class="she" title="小web" />

alert(unXpath( ' input#menu ' ));

// 返回<input id="menu" />

alert(unXpath( ' br ' ));

// 返回<br />

alert(unXpath( ' img[src="i.gif"] ' ));

// 返回<img src="i.gif" alt="" />

转载于:https://www.cnblogs.com/littleweb/archive/2010/11/28/1890623.html