简体   繁体   English

匹配子节点时获取父元素节点

[英]Get parent element node when child node is matched

This is my code: 这是我的代码:

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

This is my xml file: 这是我的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>

With this code I get the child node value . 使用此代码,我获得child node value

I wanted something, like when i enter in textbox any of city name : Ahemdabad , Surat , Rajkot ; 我想要一些东西,比如我在textbox输入任何城市名称AhemdabadSuratRajkot ; then its match on my xml file returns me country name like India . 然后它在我的xml文件上的匹配返回我的country name印度

Thanks! 谢谢!

Try 尝试

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

Demo: Plunker 演示: Plunker

You can use this xpath 您可以使用此xpath

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

Just replace 'Ahemdabad' with the desired city name 只需将'Ahemdabad'替换为所需的城市名称即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM