Tree structured XML in a TextArea
In the process of helping to create a more distributed architecture, I am starting to expose some of our business logic to xml calls. These discrete bits of business logic are traditionally locked up into compiled binaries, or if we are lucky, a stored procedure.
Anyway, I started to put together a central place where examples of all the calls can be shown with information about required parameters, and allow developers to actually call the service and show the returned XML. I did not like the look I was stuck with when I would try to display the resulting XML in a DIV, even with a transformation, so I wrote an iterative Javascript function that does nothing more than display the XML like IE/Firefox does when you call the XML directly. It places this XML into an HTML TextArea.
This is the required code to make it work. How you get the DomDocument is up to you, and you have to change the TextArea name to match yours, but it works slick as snot. Now I will be putting together a PHP version of my AJAX phone directory soon, so maybe I will place a TextArea on the page and render all of the responses into it. Should be cool:
// GLOBAL VARIABLE var strXml; if(domResult){ if(domResult.xml){ traverse(0,domResult.documentElement) ; // not sure where the "undefined" strings come from so we kill them f.results.value = strXml.replace(/undefined/gi, ''); }else{ f.results.value = new XMLSerializer().serializeToString(domResult) } }else{ alert('Communications Error'); } function traverse(x, tree) { if(tree.hasChildNodes()) { strXml += createSpacers(x); strXml += '< ' + tree.tagName; for(var i=0; i<tree.attributes.length;i++){ strXml += ' ' + tree.attributes[i].nodeName + '="' + tree.attributes[i].nodeValue + '"'; } strXml += '>' var bMultiDesc = bMoreThanOneDescendant(tree); if(bMultiDesc){ strXml += 'rn'; } for(var i=0; i<tree .childNodes.length ; i++){ traverse(x+1, tree.childNodes[i]); } if(bMultiDesc){ strXml += createSpacers(x); } strXml += '</' + tree.tagName + '>'; strXml += 'rn'; }else{ // we need to see if this is an empty node or a text node // if empty then we will create a "” tag if(tree.text != ‘’){ strXml += tree.text ; }else{ strXml += createSpacers(x) + ‘< ‘ + tree.tagName + ‘ />rn’ } } } function createSpacers(x){ var indentSpacers; for(i=0 ; i< =x ; i++){ indentSpacers += ‘ ‘; } return indentSpacers; } function bMoreThanOneDescendant(node){ // silly function to see if a node has more than a single text node beneath it // if it does, then I will insert a line break and display the next child indented // if not, then I will display the text value between the tags, all on one line if(node.hasChildNodes()) { var i = node.childNodes.length; if(i > 1){ return true; } else{ var node2 = node.childNodes[0]; if(node2.hasChildNodes()){ return true; }else{ return false; } } }else{ return false; } }
September 30th, 2005 at 6:49 pm
very cool!