For the last few days at work, I’ve been struggling to get an Xml document to load properly in a cross-browser friendly way. Seemingly, as is the way with all things browser related, what works in one doesn’t work in any others. There’s a lot of information on the web about how to load up xml documents, and by fiddling around with it all I have finally come up with a tidy little javascript file that works across Firefox (and Mozilla), Opera (the least friendly), and Internet Explorer.
Since it’s largely based on information already freely available on the web, I’ve decided to share it with anyone interested – so you can download it here. (Disclaimer: Use it at your own risk! Also, I do not claim to be the author of all of the code, like I said it’s based largely on information already available for free, elsewhere on the web). Keep reading for a usage example.
After including the XmlDocument.js in your page, you can create an XmlDocument by specifying a well-formatted xml string as the source:
var xmlDocument = CreateXmlDocument(sourceString);
You can then manipulate the document using standard DOM methods and attributes. As an example, lets say you have the following xml structure loaded:
<options> <option text="Option 1" value="One" /> <option text="Option 2" value="Two" /> </options>
Now lets say you want to parse all the “option” nodes in the document, and create a Html Option element to be put into a Html Select element called “selector”. This is one way you could do it:
// Get the Html Select var selector = document.getElementById("selector"); // Create the xml document var xmlDocument = CreateXmlDocument(sourceString); // Loop through each option node var root = xmlDocument.firstChild; for (var i = 0; i < root.childNodes.length; i++) { var node = root.childNodes[i]; // Create the option element var option = document.createElement("option"); option.text = node.attributes.getNamedItem("text").nodeValue; option.value = node.attributes.getNamedItem("value").nodeValue; // Append the option to the end of the list selector.options[selector.options.length] = option; }
Simple, eh?



No comments. Be the first!