iYoue
iYoue

Reputation: 45

How to retrieve xml data with value specified into selection tags with condition if() using javascript

My school.xml file contain the following data:

    <?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>

My html code:

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

I want to fetch data by value, i.e if value="An Giang" show option tags with school name in An Giang city:

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

</div>

How can I get this? Any solution please, Thank you ..

Upvotes: 0

Views: 159

Answers (1)

Khalid
Khalid

Reputation: 4808

suppose you have your xml as a string, you can use this code snippet to get the xml element concerned

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];
       }
    }

}

Upvotes: 1

Related Questions