Skip to content

Instantly share code, notes, and snippets.

@glenngillen
Last active August 29, 2015 14:10
Show Gist options
  • Save glenngillen/ba3a17ea0bb2a5f23ae2 to your computer and use it in GitHub Desktop.
Save glenngillen/ba3a17ea0bb2a5f23ae2 to your computer and use it in GitHub Desktop.
Swagger UI with XML
$(function () {
var basepath = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
window.swaggerUi = new SwaggerUi({
url: basepath + '/swagger.json';,
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post'],
onComplete: function(swaggerApi, swaggerUi){
log("Loaded SwaggerUI");
// Initialize an XMLSerializer that we can re-use for
// each code block
var serializer = new XMLSerializer();
// Find all of the model-signatures that have a JSON
// model definitions
$('.model-signature code.json').each(function() {
// Extract the text from the code block, it's the
// JSON definition of this model
var jsonText = $(this).text();
// Use the Mozilla JXON library to turn that
// JSON into an XML definition
var xml = JXON.unbuild(JSON.parse(jsonText));
// Now use the XML Serializer to turn it back
// into some text
var xmlText = serializer.serializeToString(xml);
// Pass XML text into indentXML() to add carriage
// returns and indentation so it's easier to read
// examples on page. Then update the current element
// to have our nicely formatted XML. $.text() takes
// care of escaping all the the < and > characters
// for us.
$(this).text(indentXML(xmlText));
// This code block doesn't show JSON any more, so
// remove the class and update it to XML.
$(this).removeClass("json");
$(this).addClass("xml");
// And re-run the syntax highlighting
hljs.highlightBlock(this)
});
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
sorter : "alpha"
});
window.swaggerUi.load();
});
/*\
|*|
|*| JXON framework - Copyleft 2011 by Mozilla Developer Network
|*|
|*| Revision #1 - September 5, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/JXON
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
\*/
const JXON = new (function () {
const
sValProp = "keyValue", sAttrProp = "keyAttributes", sAttrsPref = "@", /* you can customize these values */
aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i;
function parseText (sValue) {
if (rIsNull.test(sValue)) { return null; }
if (rIsBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
if (isFinite(sValue)) { return parseFloat(sValue); }
if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
return sValue;
}
function EmptyTree () {}
EmptyTree.prototype.toString = function () { return "null"; };
EmptyTree.prototype.valueOf = function () { return null; };
function objectify (vVal) {
return vVal === null ? new EmptyTree() : vVal instanceof Object ? vVal : new vVal.constructor(vVal);
}
function createObjTree (oParentNode, nVerb, bFreeze, bNesteAttr) {
const
nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(),
bAttributes = oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2);
var
sProp, vContent, nLength = 0, sCollectedTxt = "",
vResult = bHighVerb ? {} : /* put here the default value for empty nodes: */ true;
if (bChildren) {
for (var oNode, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) {
oNode = oParentNode.childNodes.item(nItem);
if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
else if (oNode.nodeType === 1 && !oNode.prefix) { aCache.push(oNode); } /* nodeType is "Element" (1) */
}
}
const nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt);
if (!bHighVerb && (bChildren || bAttributes)) { vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; }
for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) {
sProp = aCache[nElId].nodeName.toLowerCase();
vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr);
if (vResult.hasOwnProperty(sProp)) {
if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
vResult[sProp].push(vContent);
} else {
vResult[sProp] = vContent;
nLength++;
}
}
if (bAttributes) {
const
nAttrLen = oParentNode.attributes.length,
sAPrefix = bNesteAttr ? "" : sAttrsPref, oAttrParent = bNesteAttr ? {} : vResult;
for (var oAttrib, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) {
oAttrib = oParentNode.attributes.item(nAttrib);
oAttrParent[sAPrefix + oAttrib.name.toLowerCase()] = parseText(oAttrib.value.trim());
}
if (bNesteAttr) {
if (bFreeze) { Object.freeze(oAttrParent); }
vResult[sAttrProp] = oAttrParent;
nLength -= nAttrLen - 1;
}
}
if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) {
vResult[sValProp] = vBuiltVal;
} else if (!bHighVerb && nLength === 0 && sCollectedTxt) {
vResult = vBuiltVal;
}
if (bFreeze && (bHighVerb || nLength > 0)) { Object.freeze(vResult); }
aCache.length = nLevelStart;
return vResult;
}
function loadObjTree (oXMLDoc, oParentEl, oParentObj) {
var vValue, oChild;
if (oParentObj.constructor === String || oParentObj.constructor === Number || oParentObj.constructor === Boolean) {
oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 or 1 */
if (oParentObj === oParentObj.valueOf()) { return; }
} else if (oParentObj.constructor === Date) {
oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));
}
for (var sName in oParentObj) {
vValue = oParentObj[sName];
if (isFinite(sName) || vValue instanceof Function) { continue; } /* verbosity level is 0 */
if (sName === sValProp) {
if (vValue !== null && vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
} else if (sName === sAttrProp) { /* verbosity level is 3 */
for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
} else if (sName.charAt(0) === sAttrsPref) {
oParentEl.setAttribute(sName.slice(1), vValue);
} else if (vValue.constructor === Array) {
for (var nItem = 0; nItem < vValue.length; nItem++) {
oChild = oXMLDoc.createElement(sName);
loadObjTree(oXMLDoc, oChild, vValue[nItem]);
oParentEl.appendChild(oChild);
}
} else {
oChild = oXMLDoc.createElement(sName);
if (vValue instanceof Object) {
loadObjTree(oXMLDoc, oChild, vValue);
} else if (vValue !== null && vValue !== true) {
oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
}
oParentEl.appendChild(oChild);
}
}
}
/* Uncomment the following code if you want to enable the .appendJXON() method for *all* the "element" objects! */
/*
Element.prototype.appendJXON = function (oObjTree) {
loadObjTree(document, this, oObjTree);
return this;
};
*/
this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
const nVerbMask = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1;
return createObjTree(oXMLParent, nVerbMask, bFreeze || false, arguments.length > 3 ? bNesteAttributes : nVerbMask === 3);
};
this.unbuild = function (oObjTree, sNamespaceURI /* optional */, sQualifiedName /* optional */, oDocumentType /* optional */) {
const oNewDoc = document.implementation.createDocument(sNamespaceURI || null, sQualifiedName || "", oDocumentType || null);
loadObjTree(oNewDoc, oNewDoc, oObjTree);
return oNewDoc;
};
})();
</script>
<script type="text/javascript">
var indentXML = function(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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment