Parse xml tag attributes using Javascript or Jquery?

跟風遠走 提交于 2019-12-11 02:04:39

问题


I have one xml. Example XML is given below

<company sample="text">
<employee id="001" sex="M" age="20">Premshree Pillai</employee>
</company>

I need to get company attribute sample value

I am trying this method

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function() {
var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var pic = $(currLoanXml).find('company').attr('sample');
alert(pic);
};
</script>

Its Shows Undefined in my alert box.

But i can also alert this child tag its working

var pic = $(currLoanXml).find('employee').attr('id');
alert(pic);  

What is a problem. I need to get first tag attributes. Please help me.


回答1:


you need to use filter() instead of find() here because company is the root element, ie currLoanXml refers to the company element. find will look for decedent elements only

var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var pic = $(currLoanXml).filter('company').attr('sample');
alert(pic);

Demo: Fiddle




回答2:


You go too deep

$(function() {
  var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
  var sample = $(currLoanXml).attr('sample');
  console.log(sample);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


来源:https://stackoverflow.com/questions/18398579/parse-xml-tag-attributes-using-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!