Saturday, October 01, 2005

When mixing JavaScript and XML ...

… somethings things act … strangely. I was tweaking a script I use to manage podcasts (bridging the gap between iPodder and WinAmp), I needed a date formatting function. No problem, the DateFormatter from Gazingus.org is an excellent module (if you need date formatting in JavaScript, get it, it rocks).

Problem is, I’m writing Windows Scripting Host format scripts (using their XML schema and generating .wsf files) and I came across some interesting behavior in the cscript engine. If the engine incounters a ‘<’ (“less than”) symbol in a JScript block, it bombs with the following error:

Windows Script Host: Expecting a valid name

Even more irritating, you’ll get the error even if you comment out the offending line (doesn’t matter which way you do it, line comments (//) or comment block (/* … */) … which tells me that it’s the XML parser part of the engine that’s barfing (it doesn’t get to the JScript engine). This took a little while to figure out … and if you think like an XML parser, it (sort of) makes sense: it hits the ‘<’, thinks a new XML element is being started, and doesn’t like what it sees next (in the case of the date formatter, it usually was a number).

Ok, fine. Now what? Well, the solution (at least, my solution … I’m sure there are others out there that are more elegant) was to rewrite the logic converting all less-than comparisons to an equivalent greater-than comparison. For example:

formats['DD'] = ( date < 10 ) ? '0' + date : date;

becomes

formats['DD'] = ( 10 > date ) ? '0' + date : date;

and so forth. The logic still holds … it lets you plug it into a WSH file without generating a parser error … and it’s still a cool chunk of code.

Save yourself the trouble of rewriting Gazingus’ script, here’s a copy with the “patches”. I’ll post my iPodder script after I add some comments.

del.icio.us: