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>
复制代码

 

posted @   jasen.kin  阅读(662)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示