javascript Xml兼容性随笔
一、前言
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | ( function (window) { if (!window.jasen) { window.jasen = {}; } if (!window.jasen.core) { window.jasen.core = {}; } //------------------------------------------------ // XML operation below. //------------------------------------------------ if (!window.jasen.core.Xml) { window.jasen.core.Xml = {}; } if ( typeof jasen.core.Xml != "object" ) { throw new Error( "Invalid entity jasen.core.Xml!" ); } function createXmlDocument() { //IE if (window.ActiveXObject) { return new ActiveXObject( "Microsoft.XMLDOM" ); } //W3C else if (document.implementation && document.implementation.createDocument) { return document.implementation.createDocument( '' , '' , null ); } throw new Error( "Xml is not supported by your brower!" ); } function loadXmlFile(xmlFile) { var xmlDocument = createXmlDocument(); xmlDocument.async = false ; xmlDocument.load(xmlFile); return xmlDocument; } function loadXmlText(xmlText) { // IE Must be tested first<br> <br> if (window.ActiveXObject) { var xmlDocument = new ActiveXObject( "Microsoft.XMLDOM" ); xmlDocument.async = false ; xmlDocument.loadXML(xmlText); return xmlDocument; } // W3C else if (window.DOMParser) { return ( new DOMParser()).parseFromString(xmlText, "text/xml" ); } throw new Error( "Xml is not supported by your brower!" ); } var Xml = window.Xml = window.jasen.core.Xml; Xml.createDocument = createXmlDocument; Xml.loadFile = loadXmlFile; Xml.loadText = loadXmlText; })(window); |
二、范例
<script language="javascript" type="text/javascript"> function testXml() { var xmlDoc = Xml.loadFile("/Xml/House.xml"); var xmlDocElement = xmlDoc.documentElement; var nodes = xmlDocElement.getElementsByTagName("city"); var currNode = null; for (var i = 0; i < nodes.length; i++) { currNode = nodes[i] } var xmlText = "<address><city name='北京'><price>150万</price><type>一室三居</type></city></address>"; xmlDocElement = Xml.loadText(xmlText); var cityName = xmlDocElement.selectSingleNode("address/city/@name").nodeValue; var price = xmlDocElement.selectSingleNode("address/city/price/text()").nodeValue; } </script>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】博客园携手 AI 驱动开发工具商 Chat2DB 推出联合终身会员
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步