來公司這么長時(shí)間一直到現(xiàn)在一直在iaas項(xiàng)目中輾轉(zhuǎn)。
利用xml的特性將數(shù)據(jù)獨(dú)立出,達(dá)到UI和Db真正的分離。
1 了解知識:
1.xsl是xml的格式文件, xml是數(shù)據(jù)文件
2 調(diào)試方法:
1)在xsl內(nèi)容中嵌套javascript從而簡介調(diào)試查看xsl的中間結(jié)果,通過查看xsl+xml形成的結(jié)果htm
2)vs自帶了一個(gè)功能強(qiáng)大的調(diào)試器,專門針對此用法如下:(不懂可以問msdn)
namespace 調(diào)試 { class Program { static void Main(string[] args) { XslCompiledTransform xslt = new XslCompiledTransform(true);//true 開啟調(diào)試 // load the style sheet. xslt.Load("demo.xsl"); xslt.Transform("demo.xml", "demo.htm"); Console.Read(); } } }
適當(dāng)加斷點(diǎn),可跳進(jìn)xsl中的循環(huán)調(diào)試,也可以變量監(jiān)視。很好用。
2 Javascript結(jié)合xsl xml
xsl和xml你都有了, 如何將格式套用入數(shù)據(jù)?
1 跨域加載xml
此時(shí),倘若你想要的xml涉及跨域問題,那么在輸出xml的服務(wù)器上必須加Header。Access-Control-Allow-Origin: * 。ㄒ?yàn)榇藛栴}困然我兩天)你才能訪問到該xml,否則firfox下無法讀取。因?yàn)閕e下,設(shè)置interne選項(xiàng)中參數(shù)便可以訪問!具體問google或者私密我。
加載文件如下:
//讀取本地?cái)?shù)據(jù) function xmlGetResponse(_url) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET", _url, false); xmlhttp.send(); return xmlhttp.responseXML; //如果responseXML內(nèi)無數(shù)據(jù) 可查看responeText核查 }
其中如果responseXML.xml='' &&responseText不為空?蓪esponseText轉(zhuǎn)化為dom,返回是結(jié)果一樣的。
if (!xhttp.responseXML.xml) { //轉(zhuǎn)化為dom try { if (window.ActiveXObject) { var xmlobject = new ActiveXObject("Microsoft.XMLDOM"); xmlobject.async = "false"; xmlobject.loadXML(xhttp.responseText); return xmlobject; } else {//firfox下特殊 var parser = new DOMParser(); var xmlobject = parser.parseFromString(xhttp.responseText, "text/xml"); return xmlobject; } } catch (e) { }
2 加載xsl
加載方式同加載xml一樣,xsl也是標(biāo)簽語言哦,成雙成對的。
2 二者結(jié)合
用代碼說話:
function xmlGetResponse(_urlxml, _urlxsl) { var xml = loadXMLDoc(_urlxml);//加載xml var xsl = loadXMLDoc( _urlxsl);//加載xsl if (window.ActiveXObject) { //ie ex = xml.transformNode(xsl);//結(jié)合,結(jié)果ex是形成的htm } else if (document.implementation && document.implementation.createDocument) { //其他瀏覽器如firfox xsltProcessor = new XSLTProcessor(); xsltProcessor.importStylesheet(xsl); resultDocument = xsltProcessor.transformToFragment(xml, document); document.getElementById(id).appendChild(resultDocument); //結(jié)合,結(jié)果resultDocument是形成的htm } }
3 xml+xsl ->tree!形成樹
主要的xsl邏輯代碼我會(huì)共享給大家,也算是我這兩天的埋頭研究沒有浪費(fèi)。
1)主要思路
a.找到根節(jié)點(diǎn),便利其子節(jié)點(diǎn),其中讀取屬性等等你需要的值,并輸出(根據(jù)要求可以加上js效果)
b.遞歸循環(huán)找出所有子節(jié)點(diǎn)并展現(xiàn)出樹的層次
c.我認(rèn)為最難的點(diǎn):輸出樹節(jié)點(diǎn) 前方的虛線。不知能否理解。如果你有用到,你就知道
2)主要難點(diǎn)
a.模塊的調(diào)用和傳參! 形成遞歸(不用遞歸當(dāng)然更好)
b.計(jì)數(shù) 當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn),父節(jié)點(diǎn)的兄弟節(jié)點(diǎn),父節(jié)點(diǎn)的子節(jié)點(diǎn)中在本節(jié)點(diǎn)之后兄弟節(jié)點(diǎn)。。。。等等
最好慢慢研究http://www.w3school.com.cn/xpath/和http://www.w3school.com.cn/xsl/
說的簡潔但是意義很大。慢慢理解。
c.遞歸輸出前方虛線圖片。
由于時(shí)間限制,講的比較籠統(tǒng)。見諒