Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Created April 9, 2012 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamranayub/2346014 to your computer and use it in GitHub Desktop.
Save kamranayub/2346014 to your computer and use it in GitHub Desktop.
jQuery formatXml plugin
// XML Formatter
// =============
// A small jQuery plugin that works in conjunction with [jquery.xml](https://github.com/kamranayub/jQuery-XML-Helper) to format
// an XML DOM structure.
//
//
// Usage:
// ------
//
// $(function () {
// var $xml = $.xml("<foo attr='foo'><bar></bar></foo>");
//
// $("#xmlOutput").formatXml($xml);
// });
(function ($) {
$.fn.formatXml = function ($xml) {
return this.each(function () {
var // Element container
$container = $(this),
// Recursive traversal function
traverse = function($node, $container) {
var $ul = $("<ul />"),
$li = $("<li />");
$li.append('<strong>' + $node[0].tagName + '</strong>');
$ul.append($li);
$container.append($ul);
// Find any attributes
if ($node[0].attributes.length) {
var $attrs = $("<ul />");
$.each($node[0].attributes, function(i, attr) {
$attrs.append("<li><em>@" + attr.name + "=<span>\"" + attr.value + "\"</span></em></li>");
});
$li.append($attrs);
}
// Text nodes
if ($node.children().length == 0 && $node.text().length) {
$li.append("<ul><li>" + $node.text() + "</li></ul>");
}
// Traverse children (if any)
if ($node.children().length > 0) {
$node.children().each(function(i, node) {
traverse($(node), $li);
});
}
};
// Traverse the XML tree
$container.empty();
traverse($xml, $container);
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment