Jump to content

Displaying Multiple instances of xml tags in a table using javascript


Guest Giz
 Share

Recommended Posts

I am very new to xmlDOM and javascript. I have spent several days going through the tutorials here. I have come to a spot that i cant seem to get right. In my code i am trying to access data in an xml file and display it in a javascript table. The reason i am doing this is for cross browser compatability. If someone has a better suggestion about that then let me know. My real problem is i cant seem to get the page to display the single instance of the "name" tag with the multiple instances of the "component" tag that are in the xml. I realize that "document.write(x.getElementsByTagName("component")[0].childNodes[0].nodeValue);" line is incorrect because there should not be [0] for the childNode, but i dont know what to use in order to cycle through the other tags that are present. Help is much appriciated. :)

<script language="javascript" type="text/javascript">var xmlDoc;if (window.ActiveXObject)  {// code for IE  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");  }else if (document.implementation.createDocument)  {// code for Firefox, Mozilla, Opera, etc.  xmlDoc=document.implementation.createDocument("","",null);  }xmlDoc.async=false;xmlDoc.load("craftables.xml");document.write("<table border='0' >");var x=xmlDoc.getElementsByTagName("item");for (var i=0;i<x.length;i++){ document.write("<tr>");document.write("<td>");document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);document.write("</td>");document.write("<td>");document.write(x[i].getElementsByTagName("component")[0].childNodes[0].nodeValue);document.write("</td>");document.write("</tr>");}document.write("</table>");</script>

Link to comment
Share on other sites

childNodes returns a NodeList object (you know, like with getElementsByTagName). Having said that, you can loop over it like you've looped over all "item" elements, i.e.

document.write("<td><ul>");var y = x[i].getElementsByTagName("component")[0].childNodes;for (var e=0,var l = y.length; e<l;e++) {document.write("<li>" + y[e].nodeValue + "</li>");}document.write("</ul></td>");

(adjusted a little for slightly better performance... as the XML file grows, this will start to matter more)Be advised that it's not good to use document.write, and in general - it's not good to modify the document tree that often. You should instead perform all the looping, storing all the HTML in a variable, and then append everything with the "innerHTML" of an element of your choise.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...