使用xpath获取所有属性值

时间:2013-03-21 09:25:48

标签: xpath

这是我的xml文件: -

<results value="1">
    <result value="111">
        <Country_Code value="IN"/>
        <Country_Name value="India"/>
        <Region_Name value="Gujarat"/>
        <City  value="Rajkot"/> 
        <loction lat="13.060422" lng="80.24958300000003"/>
    </result>
    <result value="222">
        <Country_Code value="KE"/>
        <Country_Name value="Kenya"/>
        <Region_Name value="Vihiga"/>
        <City value="Kakamega"/> 
        <loction lat="0.1182473" lng="34.7334515999997"/>
    </result>
</results>

这是我的代码: -

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        var xml;
        $.get(
        "sea.xml",
        null,
        function (data) {
            xml = data;
        },
        "xml"
    );

        function get_list(ls) {
            var elName = $('#select').val();
            var value = $('#value').val();
            if(elName == "" || value == "")
            {
            }
            else if (elName != "" || value != "")
            {
            var xPath = '//*[ @lat '+ ls +' "'+elName+'" and @lng '+ ls +' "'+value+'"]'+'/../City/@*';


            var iterator = xml.evaluate(xPath, xml.documentElement, null,
                XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
            var thisNode = iterator.iterateNext();
            var str = '';
            while (thisNode) {
                if (str) {
                    str += ', ';
                }
                str += thisNode.textContent;
                thisNode = iterator.iterateNext();
            }

            $("#result").text(str);
        }
        else 
        {}
        }
    </script>
</head>
<body>
    <input type="text" id="select">
    <input type="text" id="value">
    <input type="button" name="button" value="Search" onclick="get_list('=')">
    <div id="result">
    </div>
</body>
</html>

使用此代码xpath返回属性值Rajkot但我想在Xpath中更改以获取所有属性

在xPath的帮助下,如果xml文件上的值匹配,则仅返回city属性值 但我希望所有的属性值如: - IN,Inida,Gujarat,Rajkot,13.060422,80.24958300000003

1 个答案:

答案 0 :(得分:1)

以下XPath:

//loction[@lat='13.060422' and @lng='80.24958300000003'][1]/preceding-sibling::City/@value

输出:

 value="Rajkot"

以下XPath:

//loction[@lat='13.060422' and @lng='80.24958300000003'][1]/preceding-sibling::*/@*

输出:

 value="IN"
-----------------------
value="India"
-----------------------
value="Gujarat"
-----------------------
value="Rajkot"