Displaying XML Data from other Web Sources as HTML using XSL, Part 3By Brandon Monahan
In Part 2 we looked at XSL, which is responsible for rendering XML data. In this part we'll examine more features of XSL!
Another XLS tag we will be using allows us to loop through the XML document so we get all of the information sent in the XML document. The syntax is simply this:
This can easily be used in our example XML like the following:
This will loop through each channel and we could write out the name of the channel like so:
Notice a couple of things. First, note the
@ in the value-of statement. This is the syntax for
grabbing attribute values from an XML tag. The format is simply
The second thing to notice is that we must have the ending tags even though it seems a little ridiculous. The
designers of XML agree with us so they give an easy way out; use a forward slash (
/) at the end of
the tag to specify that the end tag would have been next anyway. Below is what our code could look like:
Also you might have noticed that our
<xsl:value-of select="@title"/> tag did not contain any
directory structure. That is, using the direction I gave above, shouldn't it look like
<xsl:value-of select="newsfeed/channel/@title"/>? The answer is no. Because you have already
navigated to the appropriate element with
<xsl:for-each select="newsfeed/channel"> you only
need to refer to the relative position of the data you choose to display.
This makes for an interesting syntax, the last you will need to learn for this lesson. How can you get the value of that element when you have already navigated to that element earlier on? For example:
As you can see above, we already navigated to our headline element inside the loop statement. To then display
the value of the headline tag, it is necessary to use
<xsl:value-of />. That will give the
value of the current element.
Ok, ok, there is one more smidgen of syntax you need to learn; how to create a hyperlink from XML. Because
XML tags can not be embedded in HTML (such as
<a href="<xsl:value-of select="@href"/>">)
it is necessary to have special syntax to make links. That syntax is as follows:
Simply stated, use
<A> then place the attribute of
href and then print the
value of the
href and then print the value of the text you want to be in the
and then close everything up. And then, it magically works.
Now that we've looked at XML and using XSL to render properly formatted XML, it's time that we show how to use XSL to display the XML provided by iSyndicate.com. In Part 4 we'll look at how to accomplish this!