PDA

View Full Version : How do I get only certain elements that have the same tag name?


dnslnsyjhnsn
02-27-2010, 08:25 PM
This is my xml file:

<data>
<producers>
<operation id="987987234" timecode="20100711">
<name>Joe Shmoe</name>
<cert>0988987234</cert>
<exp>July 11th, 2010</exp>
</operation>
</producers>
<handlers>
<operation id="987987234" timecode="20100711">
<name>Sally Shmoe</name>
<cert>0988987234</cert>
<exp>May 11th, 2010</exp>
</operation>
</handlers>
</data>

This is the script to display it on my website:

<script type="text/javascript">
document.write("<h4>Producers</h4><hr />");
var x=xmlDoc.getElementsByTagName("operation");
for (i=0;i<x.length;i++)
{
document.write("Name: " + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br />");
document.write("Certification Number: " + x[i].getElementsByTagName("cert")[0].childNodes[0].nodeValue + "<br />");
document.write("Expiration Date: " + x[i].getElementsByTagName("exp")[0].childNodes[0].nodeValue + "<hr />");
}

document.write("<h4>Handlers</h4><hr />");
var x=xmlDoc.getElementsByTagName("operation");
for (i=0;i<x.length;i++)
{
document.write("Name: " + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br />");
document.write("Certification Number: " + x[i].getElementsByTagName("cert")[0].childNodes[0].nodeValue + "<br />");
document.write("Expiration Date: " + x[i].getElementsByTagName("exp")[0].childNodes[0].nodeValue + "<hr />");
}
</script>

I'm able to loop through and display all of the information by using getElementsByTagName("operation") and then displaying everything, my problem is that I need to be able to distinguish between producers and handlers and I don't know how to do that. All of the information I've been searching through seems to have their xml file has categories or something else different. Another program creates this xml file though, so it would be really troublesome to change it. Right now it goes through twice and displays all of the entries as producers and handlers. Any help would be much appreciated. Would this be more appropriate in the xml DOM or this the proper place?

abduraooft
02-28-2010, 12:30 PM
Try var x=xmlDoc.getElementsByTagName("operation");
for (i=0;i<x.length;i++)
{
if(x[i].parentNode.nodeName=='producers')
alert('producers');
else
alert('handlers');
}

drhowarddrfine
02-28-2010, 05:36 PM
<aside>
This is so easy in xslt and could be done with just 3 elements on 3 lines (off the top of my head).
</aside>