Reputation: 811
My XML structure looks a bit like this:
<Bookmark>
<Type>Media</Type>
<Name>YouTube</Name>
<Link>https://www.youtube.com</Link>
</Bookmark>
<Bookmark>
...
</Bookmark>
...
What I want to do is to display in html a table where the bookmark Name
is displayed in a column according to the Type
of bookmark that it is (i.e. a column for media bookmarks, a column for work bookmarks etc) and that name is a link to the address provided by Link
.
This is what I have so far (modified from w3schools):
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","xml/bookmarks.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.write("<table>");
var x = xmlDoc.getElementsByTagName("Bookmark");
for (i = 0; i < x.length; i++)
{
document.write("<tr><td>");
if (x[i].getElementsByTagName("Type")[0].childNodes[0].nodeValue == "Social")
{
document.write(x[i].getElementsByTagName("Name"[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
}
document.write("</table>");
</script>
This displays all the social bookmarks as I wanted. The part I am struggling with is making the results a link and applying my CSS to them.
Maybe I am going about this the wrong way totally, any advice would be appreiciated (note: my next to do item is to allow a web based interface to add and delete bookmarks - is this possible using the same techniques as below or do I need to go into XQuery or something similar?)
Upvotes: 0
Views: 109
Reputation: 6384
If you want a column per bookmark type, I'll suggest you to store each bookmark set (media, etc.) in an array, and then generate your table by browsing your arrays (i.e. for each <tr[i]/>
write <td>media[i]</td>
, <td>work[i]</td>
, etc.). Of course be carreful with the size of your arrays (no more bookmarks = empty cells).
To write a link, you can write this :
document.write("<a href=\"" + x[i].getElementsByTagName("Link")[0].childNodes[0].nodeValue + "\">";
document.write(x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue);
document.write("</a>");
There are several ways to apply a css to this table. If you want to apply it only to this table, you can write :
document.write("<table id=\"bookmarks\">");
Then in your CSS (for example):
#bookmarks {/* stuff */}
#bookmarks tr {/* trs stuff */}
#bookmarks td {/* tds stuff */}
/* whaterver */
Maybe I didn't catch your real question. Can you tell more about your issue ?
Another point : I don't understand why you're using document.write()
... Have you heard about HTML DOM reference to edit dynamically HTML content ?
Upvotes: 1
Reputation: 60007
You best bet is to use XSLT. This will transform the XML into HTML. Use CSS to style this HTML.
See http://www.w3schools.com/xsl/xsl_client.asp for the code.
Upvotes: 1