javascript Xml兼容性随笔
一、前言
(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
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>