如果输入的值和xml值相同,则显示xml文件的第一个元素

时间:2013-03-09 11:51:26

标签: html xml xpath

这是我的xml示例: -

<products>
    <product_id value="1">
        <tab_id value="351">
            <date value="30-09-1989" />
        </tab_id>
    </product_id>   
    <product_id value="2">
        <tab_id value="352">
            <date value="03-03-1990" />
        </tab_id>
    </product_id>
</products>

这是我试过的: -

<html>
    <head>
    <title>Less,Grater,Equal</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        var xml;
        $.get(
        "xml_Converted.xml",
        null,
        function (data) {
            xml = data;
        },
        "xml"
            );
            function get_list()
            {
                var ename = $('#select').val();
                var xPath = '//*["' + ename + '" = ' +
                            ' //date/@value'  + '"]/../../@value';
                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);
        }
    </script>
        <body>
        <input type="text" id="select">
        <input type="button" value="search">
        <div id="result"></div>
        </body>
    </head>
</html>

这里我想o / p如果用户在文本框中输入日期然后在xml树上匹配它的soud返回xml树的第一个元素attribut值(product_id值)o / p是1

1 个答案:

答案 0 :(得分:0)

更改此内容:

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();
}

到此:

var node = xml.evaluate(xPath, xml.documentElement, null,
                  XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var str = node.singleNodeValue ? node.singleNodeValue.textContent : '';

应该这样做。