zoukankan      html  css  js  c++  java
  • X-path使用方法

    X-path是用来在xml中查找信息的语法,用于在xml中通过属性和节点来进行导航。因为xml实际上是用来为html更新数据的,所以一般xpath就用来提供数据路径,那么我们使用的时候就需要利用js等脚本来加载,常见方法如下,其实和Ajax是一样的套路:

    首先,需要加载xml文档:

    针对大多数现代浏览器的代码

    var xmlhttp=new XMLHttpRequest()

    针对IE5和6的代码

    var xmlhttp=new ActiveXObject("Mocrosoft.XMLHTTP")

    封装函数:

    function loadXMLDoc(dname){
                    if(window.XMLHttpRequest){
                        xhttp=new XMLHttpRequest();
                    }else{
                        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xhttp.open("GET",dname,false);
                    xhttp.send("");
                    return xhttp.responseXML;
                }
                xml=loadXMLDoc("/example/xmle/books.xml");

    接着,选哟选取节点

    Internet Explorer使用selectNodes方法从XML文档中选取节点

    xmlDoc.selectNodes(xpath);

    火狐,谷歌,Opera,Safari则是使用evaluate方法

    xmlDoc.evaluate(xpath,xmlDoc,null,XPathResult).ANY_TYPE,null);

    下面是一个从xml中选取所有title的例子:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
        </head>
        <body>
            <script type="text/javascript">
                //第一步加载xml文档
                function loadXMLDoc(dname){
                    if(window.XMLHttpRequest){
                        xhttp=new XMLHttpRequest();
                    }else{
                        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xhttp.open("GET",dname,false);
                    xhttp.send("");
                    return xhttp.responseXML;
                }
                xml=loadXMLDoc("/example/xmle/books.xml");//加载xml文档
                path="/bookstore/book/title"//定义路径
                //code for IE 
                if(window.ActiveXObject){
                    var nodes=xml.selectNodes(path);//从xml中获取需要的元素
                    for (i=0;i<nodes.length;i++){
                        document.write(nodes[i].childNodes[0].nodeValue);
                        document.write("<br/>");
                    }
                }
                //code for Mozilla,Firefox,Opera,etc
                else if(document.implementation&&document.implementation.createDocument){
                    var nodes=xml.evaluate(path,xml,null,XPathResult.ANY_TYPE,null);
                    var result=nodes.iterateNext();
                    
                    while(result){
                        document.write(result.childNodes[0].nodeValue);
                        document.write("<br/>");
                    }
                }
            </script>
        </body>
    </html>
  • 相关阅读:
    Pieczęć(模拟)
    【并查集】关押罪犯
    火车进栈
    独木舟上的旅行
    哈尔滨理工大学第八届程序设计团队赛K题
    [数学、递推]Everything Is Generated In Equal Probability
    [构造]triples I
    2019牛客第三场
    [DP]销售
    [哈夫曼树]猜球球
  • 原文地址:https://www.cnblogs.com/runhua/p/7197879.html
Copyright © 2011-2022 走看看