2

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Arun P Johny..Instead of, I using javascript how can i get title from xml file ?
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.