Why is XML Such a Pain in JavaScript?

Why is it that when one tries to parse some fairly simple xml:

<placemarks>
	<placemark>
		<name>Placemark 1</name>
		<latitude>-79.00</latitude>
		<longiude>42.00</longitude>
	</placemark>
	<placemark>
		<name>Placemark 2</name>
		<latitude>-129.00</latitude>
		<longiude>43.00</longitude>
	</placemark>
</placemarks>

For example, iterating through all the placemarks and extracting the names, lats and longs using javascript is a very tedious affair. In fact, I’ve found it almost pointless to even try without my head exploding.

All of the examples I’ve seen that parse XML in javascript with any ease all use the attributes of XML items.  If this were the case, I’d be using an XML file that looks something like this.

<placemarks>
	<placemark name="Placemark 1" latitude="-79.00" longiude="42.00" />
	<placemark name="Placemark 2" latitude="-129.00" longiude="43.00" />
</placemarks>

That’s a piece of cake with JavaScript, but you know what? Using attributes for every bit of data you want isn’t that bright of an idea.  The schema isn’t very extensible if you use attributes for all of your data points.  What if I want to add a ‘description‘ to each point, and I want that description to contain an HTML fragment? Using an attribute is out of the question for that.

So, What’s an easy way to parse my well built XML file?  I don’t know yet, I’m still looking for that answer.  For the time being I’m using Zend Framework’s Zend_Json to encode the XML output that I generate and return a JSON object.  Maybe this is actually the best way to do it.  After all, JavaScript parsing JSON is fast and super-easy.

Zend_Loader::loadClass('Zend_Json');
$json = Zend_Json::fromXML($xml);

And, pewf I’ve got JSON.

I guess the whole point of this is, does anybody actually know a good way to to parse XML with JavaScript without using attributes for all the datapoints?

Until then, JSON it is.

You can leave a response, or trackback from your own site.

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!