2013-04-20 138 views
0

這是我的代碼:獲取父元素節點時,子節點匹配

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script> 
var xml; 
$.get(
    "code.xml", 
    function(data) { xml=data; }, 
    "html" 
); 
function get_list(){ 
    xmlDoc = $.parseXML(xml), 
    $xml = $(xmlDoc), 
    $title = $xml.find('[value="'+$('#select').val()+'"]'); 
    $nodes = $title.find('*'); 
    var result=''; 
    $nodes.each(function(){ 
    result += $(this).attr('value'); 
    result += ' '; 
    }); 
    $("#result").html(result); 
} 
</script> 
</head> 
<input type="text" id="select"> 
<input type="button" name="button" value="Search" onclick="get_list()" > 
<div id="result"> 
</div> 
</html> 

這是我xml文件:

<root> 
    <child_1 entity_id = "1" value="india"> 
     <child_2 entity_id = "2" value="gujarat"> 
      <child_3 entity_id = "3" value="Ahemdabad"/> 
      <child_4 entity_id = "4" value="Surat"/> 
      <child_5 entity_id = "5" value="Rajkot"/>   
     </child_2> 
    </child_1> 
    <child_6 entity_id = "6" value="Rasia"> 
     <child_7 entity_id = "7" value="state"> 
      <child_8 entity_id = "8" value="cty"/> 
      <child_9 entity_id = "9" value="cty1"/> 
      <child_10 entity_id = "10" value="cty2"/>   
     </child_2> 
    </child_6> 
</root> 

有了這個代碼,我得到的child node value

我想要的東西,當我在textbox任何城市名稱輸入,如:Ahemdabad蘇拉特拉傑果德;那麼它在我的xml文件上的匹配返回我country name印度

謝謝!

+0

你想要的結果是'印度' – 2013-04-20 12:27:47

回答

2

嘗試

var xml; 
$.get(
    "code.xml", 
    function(data) { 
     xml=data; 
    }, 
    "html" 
); 
function get_list(){ 
    var xmlDoc = $.parseXML(xml), 
     $xml = $(xmlDoc), 
      $title = $xml.find('[value="'+$('#select').val()+'"]'); 
    var ctrs = $xml.find('root').children(); 
    $("#result").html($title.closest(ctrs).attr('value')); 
} 

演示:Plunker

+0

它不可能'('child_1')'手冊b'coz ih ave巨大的xml文件,然後我進入只是節點2孩子就像在我的XML更新... cty然後輸出是Rasia ...所以不能手動可能... :) – 2013-04-20 12:43:08

+0

@JackPhp看到更新 – 2013-04-20 12:50:20

0

您可以使用此XPath

//*[@value='Ahemdabad']/parent::*/@value 

就與所需的城市名稱取代 'Ahemdabad'