Click here to Skip to main content
15,895,656 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have XML structure like that

XML
<employees>

 <employee id="10">
   <name>jone</name>
</employee>
 <employee id="20">
   <name>adam</name>
</employee>
 <employee id="35">
   <name>tito</name>
</employee>
</employees>



how to get the name of employee with id= 20 using jquery note that this employee my be at any position (my be 3 element or first element )

suppose that XML document stored in variable called xmfile


JavaScript
if($(xmfile).find("employee[id=10]").length > 0)
   alert($(this).html());
Posted

Try this:
JavaScript
var employees = $(xmfile).find("employee[id=20]");
if(employees.length == 1) {
    var employee = employees[0];
    var name = $(employee).find("name").text();
    alert(name);
}
else if (employees.length == 0) {
    alert("No employees found with that ID.");
}
else { // in this case, employees.length > 1
    alert("Too many employees found with that ID.");
}

How it works: it finds all employees with 20 as ID and stores them in an array. If the length of that array is one, it stores the only item in the variable employee, looks for the element name, and stores the inner text in the variable name.
 
Share this answer
 
Try this:
C#
var found = $(xmlfile).find("employee[id=20] name")
if(found.length > 0) alert(found.text());

jsfiddle[^]
 
Share this answer
 
Comments
TheSniper105 6-Feb-15 23:13pm    
simple and clean thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900