Skip to content

Instantly share code, notes, and snippets.

@kurtsson
Forked from sente/formatXML.js
Last active August 10, 2023 13:22
Show Gist options
  • Save kurtsson/3f1c8efc0ccd549c9e31 to your computer and use it in GitHub Desktop.
Save kurtsson/3f1c8efc0ccd549c9e31 to your computer and use it in GitHub Desktop.
formatXML.js but without jQuery dependency
function formatXml(xml) {
var formatted = '';
var reg = /(>)(<)(\/*)/g;
xml = xml.toString().replace(reg, '$1\r\n$2$3');
var pad = 0;
var nodes = xml.split('\r\n');
for(var n in nodes) {
var node = nodes[n];
var indent = 0;
if (node.match(/.+<\/\w[^>]*>$/)) {
indent = 0;
} else if (node.match(/^<\/\w/)) {
if (pad !== 0) {
pad -= 1;
}
} else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
indent = 1;
} else {
indent = 0;
}
var padding = '';
for (var i = 0; i < pad; i++) {
padding += ' ';
}
formatted += padding + node + '\r\n';
pad += indent;
}
return formatted.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/ /g, '&nbsp;');
}
<html>
<head>
<title>Javascript xml pretty print - Stuart Powers</title>
<script src="http://bit.ly/jqymin"></script>
<style>
textarea {
width: 80%;
height: 50%;
overflow-x: scroll;
overflow-y: scroll;
display: block;
border: 1px solid black;
padding: 5px;
margin: 5px;
}
</style>
<script>
function formatXml(xml) {
var formatted = '';
var reg = /(>)(<)(\/*)/g;
xml = xml.replace(reg, '$1\r\n$2$3');
var pad = 0;
jQuery.each(xml.split('\r\n'), function(index, node)
{
var indent = 0;
if (node.match( /.+<\/\w[^>]*>$/ ))
{
indent = 0;
}
else if (node.match( /^<\/\w/ ))
{
if (pad != 0)
{
pad -= 1;
}
}
else if (node.match( /^<\w[^>]*[^\/]>.*$/ ))
{
indent = 1;
}
else
{
indent = 0;
}
var padding = '';
for (var i = 0; i < pad; i++)
{
padding += ' ';
}
formatted += padding + node + '\r\n';
pad += indent;
});
return formatted;
}
$(function(){
var url = "http://careers.stackoverflow.com/jobs/feed?searchTerm=python&location=02144&range=30";
$.ajax({
url: url,
dataType:"text",
beforeSend:function(){$('.info').append($('<p>requesting: '+url+'</p>'));},
error:function(){$('.info').append($('<p>error! '+url+'</p>'));},
success: function(data) {
$('.unformatted').text(data);
}
});
$.ajax({
url: url,
dataType:"text",
beforeSend:function(){
$('.info2').append($('<p>requesting '+url+'</p>'));
$('.info2').append($('<p>and formatting the response!'));
},
error:function(){$('.info2').append($('<p>error! '+url+'</p>'));},
success: function(data) {
xml_neat = formatXml(data);
$('.formatted').text(xml_neat);
}
});
});
</script>
</head>
<body>
<code>
Also available <a href="http://sente.cc/misc/javascript_xml_pretty_print.html">
http://sente.cc/misc/javascript_xml_pretty_print.html
</a>
</code>
<pre class="info"></pre>
<h3>unformatted</h3>
<textarea class="unformatted"></textarea>
<h3>formatted</h3>
<textarea class="formatted"></textarea>
<body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment