IE的Xpath 获取单一节点

 var xmlDom = getXMLDOM(xmlStr);//调用之前写好的方法获得XMLDOM对象
        //        var node = xmlDom.selectSingleNode("root/user"); //获取单一节点
        //        alert(node.firstChild.nodeValue);
//        var node = xmlDom.selectSingleNode("root/user/text()"); //text()可以获取节点内的值
        //        alert(node.nodeValue);

        var node = xmlDom.selectSingleNode("//user[1]"); //双斜杠可以获取不关心层次的第一个user
        alert(node.xml);
        var node = xmlDom.selectSingleNode("root/user[@idp=5]");
        //通过唯一属性找到user节点

        alert(node.xml);

//        var nodes = xmlDom.selectNodes("root/user");
//        alert(nodes[1].xml)
View Code


下面是非IE 和IE 的Xpath 获取单个节点,兼容方法

    //做兼容,单个节点
    function selectSingleNode(xmlDom, xpath) {
        var node = null;
        //W3C
        if (typeof xmlDom.evaluate != "undefined") {
            /*此处需要将W3C标准,火狐等浏览器下的xpath【数字】加1,从而达到与IE xpath统一*/
            var patten = /\[(\d+)\]/g;
            var flag = xpath.match(patten);
            var num = 0;
            if (flag !== null) {
                num = parseInt(RegExp.$1) + 1;
                xpath = xpath.replace(patten, '[' + num + ']');
            }

            var eva = new XPathEvaluator();
            var result = eva.evaluate(xpath, xmlDom, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); //单一节点
            if (result !== null) {
                node = result.singleNodeValue;
            }
        }
        else if (typeof xmlDom.selectSingleNode != "undefined") {//IE

            node = xmlDom.selectSingleNode(xpath);
        }
        return node;

    }
View Code


下面是获取集合节点的兼容方法,更单个节点类似。使用iterateNext()方法,将eva.evaluate返回的集合放入数组,以便调用

 

   //跨浏览器,做个节点集合
    function selectSingleNodes(xmlDom, xpath) {
        var nodes = null;
        //W3C
        if (typeof xmlDom.evaluate != "undefined") {
            /*此处需要将W3C标准,火狐等浏览器下的xpath【数字】加1,从而达到与IE xpath统一*/
            var patten = /\[(\d+)\]/g;
            var flag = xpath.match(patten);
            var num = 0;
            if (flag !== null) {
                num = parseInt(RegExp.$1) + 1;
                xpath = xpath.replace(patten, '[' + num + ']');
            }
            var eva = new XPathEvaluator();
            var result = eva.evaluate(xpath, xmlDom, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); //节点集合
            var node = null;
            //下一跳节点

            var nodes = [];
            while ((node = result.iterateNext()) !== null) {
                nodes.push(node);

            }
        }
        else if (typeof xmlDom.selectNodes != "undefined") {//IE

            nodes = xmlDom.selectNodes(xpath);
        }
        return nodes;

    }
    //    alert(serializerXML(selectSingleNodes(xmlDom, "root/user")));
    alert(serializerXML(selectSingleNodes(xmlDom, "root/user")[1]));

</script>
View Code

 

 

 

 

 

posted on 2013-11-26 17:56  cpu歌歌  阅读(350)  评论(0编辑  收藏  举报