如何使用条件if()使用javascript检索带有指定值的选择标记的xml数据

时间:2015-05-05 10:52:23

标签: javascript xml

我的school.xml文件包含以下数据:

    <?xml version="1.0" encoding="UTF-8"?>
<schoolList>
    <city name="An Giang">
        <school>An Giang University</school>
        <school>An Giang 2 University</school>
    </city>
    <city name="An Thuan">
        <school>An Thuan University</school>
        <school>An Thuan 2 University</school>
    </city>
</schoolList>

我的HTML代码:

<select name="txtUnivState" id="txtUnivState">
   <option value="An Giang">An Giang</option>
   <option value="An Thuan">An Thuan</option>
</selcet>

我想按值获取数据,即如果value =“An Giang”在An Giang城市显示带学校名称的选项标签:

<div id="school" style="display: none;">
    <select name="school" id="school">
        <option value="school_name[]">school_name[]</option>
    </select>

</div>

我怎么能得到这个?请解决任何问题,谢谢..

1 个答案:

答案 0 :(得分:1)

假设您将xml作为字符串,您可以使用此代码段来获取相关的xml元素

function getData (xmlString, value) {

    var parser = new DOMParse();
    var doc = parser.parseFromString(xmlString, "text/xml");

    // now you need to look for the data with name of your choice

    var cities = doc.getElementsByTagName("city");
    for (var i = 0; i<cities.length; i++) {
       if(cities[i].getAttribute("name") == value) {
           return cities[i];
       }
    }

}