Javascript XML parser

2007-12-11

Nothing new, still comes in handy. My example was created using this example.

My script takes the text from the textarea and feeds it to the document parser of firefox/opera or some kind of XMLDOM parser of IE and generates a document (similar to the parsing of a regular html document).

Then there's a function interpreting this data and printing the tree. This is added to demonstrate how to walk through the tree. Of course you can choose to create your own tree with arrays, but that's just redundant overhead.

The code isn't 'clean', but it only serves as an example. For clean-ness go to the w3schools.com link :) The addition of my script is showing how to walk the tree (including attributes).

The reason I need this is because I need to parse XML files, but Javascript has securityrestrictions in place restricting the source of files Javascript can access to the domain or local machine, depending on where you loaded the script from. Using the textarea a user can copy-paste the contents of a xml file. This allows you to let Javascript crunch the data before feeding it to your webserver by ajax.

Limitations depend on the browser. IE and FF did not mind a ~ 1.2 mb 4 level XML file fine (even though IE did 3x as long pasting the file as parsing it). Opera threw a memmoryerror, so the limit is about ~ 1mb there. The browsers take about equal amount of time actually parsing the XML.

I haven't tested the script on 'slow' machines. This is a quad 6600 with 2gig ram (and it makes a difference, believe you me, so I'm curious to the behaviour of older machines).