The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. September 16, 2019, 09:30:40 PM

Login with username, password and session length


Pages: [1]
  Print  
Author Topic: XSL for the win  (Read 12042 times)
m0nkeymafia
Expert
****
Offline Offline

Posts: 240


Check it!


View Profile
« on: May 22, 2007, 03:54:45 AM »

As promised here is my XSL tutorial / "learn it bitch" post.
XSL aka XML Stylesheet is basically a way of parsing XML to transform it into something else, that something else can be another XML document, or it can be a fragment of xhtml [the bit we are interested in].

XSL is great because it cuts out all the nasty Javascript XML handling and provides a truley portable way of transforming XML docs.

XSL is based on XML and as such generally must follow the XML spec itself.  So without further ado lets look at our first piece of XSL.

Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/FileList">
        <div><xsl:value-of select="count(*)"/> files found</div>
        <xsl:for-each select="File">
            <xsl:sort select="current()" order="descending" data-type="text" lang="en"/>
            <xsl:variable name="filename"><xsl:value-of select="current()"/></xsl:variable>
            <a href='Error/{$filename}'><img src='Graphics/bullet_disk.png' /></a> <a href='' OnClick="ShowThisFile('Error/{$filename}'); return false;"><xsl:value-of select="$filename"/></a><br />
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Ok lets step through this.
Firstly we basically define the version of XML were working with along with character set, easy stuff.
Next we define our root element and also let the XSL parser know which namespace we are using, this never really changes.

OK onto the harder stuff, before we go here we should take a quick look at the XML being parsed by the XSL:
Code:
<FileList>
 <File>filename.png</File>
 <File>filename1.png</File>
 <File>filename2.png</File>
</FileList>

The XML is parsed as follows.
Firstly we define a template for the data, this is accomplished with <xsl:template match="/FileList">, note that XSL uses XPath to reference XML objects [if you dont know XPath shame on you! Tongue].

This basically says that whatever is a child node of "template match" will be used to process anything it matches [if that makes sense].  So if there was more than one <FileList> root node [there wont be, but if there was] then they would both get "matched" and subsequently processed by the same code.

Note you can specify template matches anywhere in your XSL.  This means you can create function like chunks of code to parse specific bits of XML.

Notice the next section of XSL is actually some xHTML with an XSL tag within, incidentally any xHTML inside your XSL document has to be properly formed else the transformation will fail.

Code:
<div><xsl:value-of select="count(*)"/> files found</div>
This will output the number of nodes in the current "directory" [we are talking XPath here] aka nodes at a given level

Next is a self explanitory for loop
Within that is a tag that sorts the data as and how we want it

Code:
<xsl:variable name="filename"><xsl:value-of select="current()"/></xsl:variable>
This declares a variable for use later, we put the value of current() [which is the current nodes data] into "filename" which can be accessed via $filename.

So then now we actually output a link with some javascript [that I use in to show the file when you click it, so not important here].
Note how we can use $filename within attributes of elements directly.  But if we want to output the variable outside of an attribute we need to use <xsl:select>.

Ok well that is a basic example, but the real power comes when you learn how all the pieces fall together.
For example, as XSL is an open standard it is not language specific, meaning itll parse the same in all languages, i.e. php and javascript.

Also you can directly modify the stylesheet from JS using "params".  As a quick example this means you could do the following:
Download an XML of data from your server, store client side via JS
Render the XML using XSL into a cool table for your user.
They click on a sort column, you use javascript to alter a param value within the XSL and reparse the original XML file
A fraction of a second later the data is resorted and the user smirks to himself wondering how you got it to do that so fast

Smiley
Hope that helped clear up what XSL is and how it is used, its a very basic example but trust me, if you do a lot of work with XML and or Ajax its WELL worth knowing, my latest project used probably 20 XSL stylesheets and I havent looked back!

Cheers
Logged

I am Tyler Durden
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #1 on: May 23, 2007, 10:00:18 AM »

MM -

I have printed but have not internalized what you've written. I think it's really important, but haven't invested enough time to respond appropriately. Just didn't want you to think that your work went unnoticed.

Thanks,
/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
m0nkeymafia
Expert
****
Offline Offline

Posts: 240


Check it!


View Profile
« Reply #2 on: May 23, 2007, 10:22:57 AM »

Haha no worries dude.
TBH im pretty crap at explaining things, I tend to skip over conjoining explanations because I know them and forget other people may not.

Any probs just drop me a PM dude
I wish I could show you an online example, but everything I do using XSL is for work, and as such never gets released onto the net.
Logged

I am Tyler Durden
nutballs
Administrator
Lifer
*****
Offline Offline

Posts: 5627


Back in my day we had 9 planets


View Profile
« Reply #3 on: May 23, 2007, 10:58:19 AM »

I wish I could show you an online example, but everything I do using XSL is for work, and as such never gets released onto the net.

i hate that. thats most of my work with my clients.
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #4 on: May 23, 2007, 11:04:40 AM »

fuck 'em & spill it! I just won't let them into the cache!  ROFLMAO
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« Reply #5 on: May 23, 2007, 06:31:06 PM »

lol, how do u get the XSL to parse the XML? For gawds sake dumb it down to the max will ya?


(yes, of course I could go look it up but what fun would that be?)

Cheers,
td
Logged

"I want to be the guy my dog thinks I am."
 - Unknown
m0nkeymafia
Expert
****
Offline Offline

Posts: 240


Check it!


View Profile
« Reply #6 on: May 24, 2007, 01:16:07 AM »

Believe it or not I love my employer, they are fairly relaxed, and just really cool [as employers go lol] so dont wanna shaft them

But, to parse your xsl / xml look here:

Firstly you need to grab your XSL document [however you like] this function is called on the response to receiving the XSL document

Note that for FF we create an XSLProcessor object, but for IE only the XML is required [the xsl transform is part of its xml classes]

Code:
function handleXSLResponse()
{
if ((http.readyState == 4) && (http.status == 200))
{
try
{
xslProc = new XSLTProcessor();
xslProc.importStylesheet(http.responseXML);
}
catch(e)
{
if (window.ActiveXObject)
{
xslProc = http.responseXML;
setTimeout(OnGotXSL, 0);
}
else
{
alert("Failed to create XSL Processor: " + e.message);
}
}

sendRequest();
}

}

Now I call this code every time I want to transform my current XML doc using the current XSL doc I have.
I do it this way so I can re-transform my data at any time, rather than only on receiving new data.
P.s. youll have to excuse my sloppy coding lol, I get it working then dont touch it Tongue

Code:
function TransformXML()
{
if (!xmlDoc) { return; }
try
{
emptyElement(document.getElementById(container));

if (window.ActiveXObject)
{
xslProc.input = xmlDoc;
xslProc.transform();
var output = xslProc.output;

if (output && xmlDoc.parseError.errorCode == 0)
{
$(container).innerHTML = output;
}
else
{
alert(xmlDoc.parseError.errorCode);
}
}
else
{
try
{
output = xslProc.transformToFragment(xmlDoc, document);
if (xmlDoc && output)
{
document.getElementById(container).appendChild(output);
}
}
catch (e)
{
document.getElementById(container).innerHTML = "Error occured transforming data: " + e.message;
}
}

//We have done the transform now lets call our "done the transform" function
//doneTransform;
setTimeout(OnTransform, 0);
output = null;
}
catch (e)
{
//alert("Error: " + e.message);
}
}
Logged

I am Tyler Durden
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« Reply #7 on: May 24, 2007, 04:54:49 AM »

Wow
Logged

"I want to be the guy my dog thinks I am."
 - Unknown
m0nkeymafia
Expert
****
Offline Offline

Posts: 240


Check it!


View Profile
« Reply #8 on: May 24, 2007, 05:22:53 AM »

Wow?

P.s. the astute among you will realise I use innerHTML every now and again, even though I flamed it in another post - figure that Tongue lol
Logged

I am Tyler Durden
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« Reply #9 on: May 24, 2007, 04:41:12 PM »

Yes, wow.
Logged

"I want to be the guy my dog thinks I am."
 - Unknown
StephenBauer
Rookie
**
Offline Offline

Posts: 36


View Profile
« Reply #10 on: June 21, 2007, 12:36:21 PM »


This is the foundation for scraper sites that scrape XML Amazon product feeds, Alexa stats, etc.  Grab the XML of the product or what not, transform it, and show it.  Not much DB work on your websites side other than maybe category management.

SB
Logged
m0nkeymafia
Expert
****
Offline Offline

Posts: 240


Check it!


View Profile
« Reply #11 on: October 08, 2007, 03:40:37 AM »

Yes, wow.

Didnt know if you were bein sarcastic Smiley

p.s. at work [read: dayjob Tongue] i had to write a program that converted xml epos data from one format to our own format, within 1 hour i had a robust reliable xml schema and transform document that could verify and then convert the xml between their format and hours.  brilliant stuff!
Logged

I am Tyler Durden
lanshan75
n00b
*
Offline Offline

Posts: 1


View Profile
« Reply #12 on: August 14, 2012, 11:25:05 PM »

Guys,do you love cats, i am a girl who love cats very much,i just want to find some new friends to share the happiness of keeping cats.
__________________________________
share love,share happy,share useful information about http://www.mmolive.com/ and http://www.mmohome.com/gold/Maple-Story-US.html
Logged
Pages: [1]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!