Parsing and traversing an XML document with jQuery
Parsing and traversing an XML document with jQuery (by Sk8erPeter)
by Anov Siradj
HTML
<h1>Parsing and traversing an XML document with jQuery</h1>
<p><small>by Sk8erPeter</small></p>
<p>The processed XML data (tagnames and values):</p>
<div id="content">
</div>
CSS
.tagname {
text-decoration:underline;
font-style:italic;
}
.tagvalue {
color:red;
}
small {
font-size:11px;
}
JavaScript
/**
* Traverse an XML Document
*
* @param xmlDoc The XML Document
* @param idOfContainerDomElement The id of the DOM element to output the processed XML tags and values to
* @initialMarginLeft The initial left margin in pixels: every time an element has childs (which means the function gets called recursively), we increase the indentation (the left margin) to keep it well-formatted and and follow the XML document's structure
*
* @author Sk8erPeter
*/
function traverseXmlDoc(xmlDoc, idOfContainerDomElement, initialMarginLeft) {
var $xmlDocObj, $xmlDocObjChildren, $contentDiv;
$contentDiv = $('#' + idOfContainerDomElement);
if ($contentDiv.length === 0) {
throw new Error('There are no DOM elements with this id: "' + idOfContainerDomElement + '"');
}
$xmlDocObj = $(xmlDoc);
$xmlDocObjChildren = $(xmlDoc).children();
if (!is_numeric(initialMarginLeft)) {
initialMarginLeft = 0;
}
else {
initialMarginLeft += 20;
}
$xmlDocObjChildren.each(function(index, Element) {
var
$currentObject = $(this),
// does it have child elements? (if yes, we should call the function recursively)
childElementCount = Element.childElementCount,
currentNodeType = $currentObject.prop('nodeType'),
currentNodeName = $currentObject.prop('nodeName'),
currentTagName = $currentObject.prop('tagName'),
currentTagText = $currentObject.text();
$contentDiv.append($('<p>', {
'class': 'tagname',
'css': {
'margin-left': initialMarginLeft
},
'html': 'Tagname: ' + currentTagName
}));
// if it has child nodes, then we call this function recursively
if (childElementCount > 0) {
traverseXmlDoc($currentObject, idOfContainerDomElement, initialMarginLeft);
}
else {
// if it doesn't have child nodes, we
...