Stackoverflow - JavaScript Recursion to format lists from XML to HTML
http://stackoverflow.com/q/15148077/918414
by Anov Siradj
HTML
<input type="button" id="parse" value="Parse" />
<ul id="result"></ul>
<script>
/* by: thinkingstiff.com
license: http://creativecommons.org/licenses/by-nc-sa/3.0/us/ */
var headerCaption = 'JavaScript Recursion to format lists from XML to HTML',
headerUri = 'http://stackoverflow.com/q/15148077/918414';
document.body.insertAdjacentHTML(
'afterBegin',
'<a href="' + headerUri + '" '
+ 'target="_top" '
+ 'onmouseover="this.style.opacity=\'.95\'" '
+ 'onmouseout="this.style.opacity=\'1\'" '
+ 'style="'
+ 'background-color: black;'
+ 'background-image: linear-gradient( top, rgba( 255, 255, 255, .3), rgba( 255, 255, 255, 0)...
CSS
#result {
list-style-type: none;
margin: 0;
padding: 0;
}
JavaScript
document.getElementById( 'parse' ).addEventListener( 'click', function () {
var xml = '<ddm>'
+ '<menu0 submenu="true"><name>Welcome</name>'
+ '<menu1>Home Page</menu1>'
+ '<menu1>Bulletin</menu1>'
+ '</menu0>'
+ '<menu0 submenu="true"><name>Members\' Area</name>'
+ '<menu1>Constitution & Bylaws</menu1>'
+ '<menu1 submenu="true"><name>AGM Minutes</name>'
+ '<menu2>2012</menu2>'
+ '<menu2>2011</menu2>'
+ '</menu1>'
+ '</menu0>'
+ '<menu0>About</menu0>'
+ '</ddm>',
xmlDoc = new DOMParser().parseFromString( xml, 'text/xml' ),
html = nodeMarkup( xmlDoc.documentElement );
document.getElementById( 'result' ).innerHTML = html;
} );
function nodeMarkup( node ){
if( node.childNodes.length ) {
var list = '', header = '';
for( var index = 0; index < node.childNodes.length; index++ ) {
if( node.childNodes[index].tagName == 'name' ) {
header = node.childNodes[index].textContent;
} else {
list += nodeMarkup( node.childNodes[index] );
};
};
return node.hasAttribute( 'submenu' )
? '<li>' + header + '<ul>' + list + '</ul></li>'
: list;
} else {
return '<li>' + node.textContent + '</li>';
};
};