Created
April 9, 2012 19:36
-
-
Save kamranayub/2346014 to your computer and use it in GitHub Desktop.
jQuery formatXml plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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