2014-02-25 18 views
0

我有一些來自某些web服務的XML數據,看起來像這樣。使用jquery在xml中搜索特定值

<?xml version="1.0" standalone="yes"?> 
<Hospitals> 

<Hospital> 
<Name>Fortis HealthCare</Name> 
<Speciality>Cardiology</Speciality> 
<Speciality>Counseling</Speciality> 
<City>Mumbai</City> 
</Hospital> 

<Hospital> 
<Name>Sagar Hospital</Name> 
<Speciality>General Dentistry</Speciality> 
<City>Bangalore</City> 
</Hospital> 

</Hospitals> 

我在HTML

<form id='search'> 
<input type='text' class=''speciality'><br> 

<input type='text' class=''area'><br> 
<input type='submit' class=''btn'> 
</form> 

基於這種搜索在兩個文本字段,我需要從XML得到醫院的完整細節。

使用jQuery我試圖讓像

function parseSearch(xml) 
{ 
//find every query value 
$(xml).find("Hospital").each(function() 
{ 
var cityName = $(this).find("City").text(); 
}); 
} 

價值,但現在我將如何從XML搜索並顯示正確的數據?

在此先感謝!

回答

1

試試這個,

function parseSearch(xml) { 
    //find every query value 
    $(xml).find("Hospital").each(function() { 
     var cityName = $(this).find("City").text(); 
     console.log(cityName);// check city name in console 
    }); 
} 
$(function() { 
    $(':submit').on('click', function (e) { 
     e.preventDefault(); 
     parseSearch(xml); 
    }); 
}); 

Live Demo

更新

function parseSearch(xml) { 
    //find every query value 
    $(xml).find("Hospital").each(function() { 
     if($(this).find('Speciality').length){// check for speciality 
      console.log($(this).text()); 
     } 
    }); 
} 

Updated Demo

+0

這裏將顯示xml。它找到cityName,那麼整個標籤在xml中得到整個標籤數據。 –

+0

使用'console.log($(this).text());'如果您希望您的標記數據爲'html',請參閱http://jsfiddle.net/tR7h9/1/然後使用'console.log($(此)的.html());'。 –

+0

但它顯示所有條目,我需要搜索用戶在文本字段中提供的特定條目。如果匹配一些,顯示完整信息 –

0
var xml = $.parseXML(yourfile.xml), 
    $xml = $(xml), 
    $test = $xml.find('test'); 
    console.log($test.text()); 

這裏測試的是xml節點名稱,比如醫院。 如需幫助: - http://www.fyneworks.com/jquery/xml-to-json/

+0

這將只顯示醫院的文字值,但在我的情況下醫院標籤有子標籤不是文字 –