Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pretty print XML output #1983

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion src/js/models/DataONEObject.js
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,12 @@ define(['jquery', 'underscore', 'backbone', 'uuid', 'he', 'collections/AccessPol
* Will format an XML string or XML nodes by camel-casing the node names, as necessary
*/
formatXML: function(xml){
var formattedXML = "";
var xsltProcessor;
var xslt;
var xsltDoc;
var xmlDoc;
var transformedDoc;
var nodeNameMap = this.nodeNameMap(),
xmlString = "";

Expand Down Expand Up @@ -1244,7 +1250,35 @@ define(['jquery', 'underscore', 'backbone', 'uuid', 'he', 'collections/AccessPol
var regEx = new RegExp("\&[0-9a-zA-Z]+\;", "g");
xmlString = xmlString.replace(regEx, function(match){ return he.encode(he.decode(match)); });

return xmlString;
// Transform the xmlString into an indented XML string
// and preserve whitespace in text nodes
xslt = [
'<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">',
' <xsl:output indent="yes"/>',
' <xsl:preserve-space elements="*"/>',
' <xsl:template match="node()|@*">',
' <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>',
' </xsl:template>',
'</xsl:stylesheet>'
].join("\n");

try {
xsltDoc = new DOMParser().parseFromString(xslt, "application/xml");
xmlDoc = new DOMParser().parseFromString(xmlString, "application/xml");

if (window.ActiveXObject || "ActiveXObject" in window) {
xsltProcessor = new ActiveXObject("Msxml2.XSLTemplate");
} else {
xsltProcessor = new XSLTProcessor();
}
xsltProcessor.importStylesheet(xsltDoc);
transformedDoc = xsltProcessor.transformToDocument(xmlDoc);
formattedXML = new XMLSerializer().serializeToString(transformedDoc);
return formattedXML;
} catch (transformError) {
console.log("Could not pretty-print XML:" + transformError);
return xmlString;
}
},

/**
Expand Down