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

Added CDATA support to the toString() #23

Closed
wants to merge 3 commits into from
Closed
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
26 changes: 22 additions & 4 deletions lib/xmldoc.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,33 @@ XmlElement.prototype.toString = function(options) {
return this.toStringWithIndent("", options);
};

function escapeValue(str, isAttribute) {
// The order of replacement is important - first process the &, than all other
str = str.replace(/&/g, '&amp;').replace(/</g, "&lt;").replace(/>/g, "&gt;");
if (isAttribute) {
str = str.replace(/"/g, '&quot;');
}
return str;
}

XmlElement.prototype.toStringWithIndent = function(indent, options) {
var s = indent + "<" + this.name;
var linebreak = options && options.compressed ? "" : "\n";

for (var name in this.attr)
if (Object.prototype.hasOwnProperty.call(this.attr, name))
s += " " + name + '="' + encodeURIComponent(this.attr[name]) + '"';
for (var name in this.attr) {
if (Object.prototype.hasOwnProperty.call(this.attr, name)) {
s += " " + name + '="' + escapeValue(this.attr[name], true) + '"';
}
}

var finalVal = this.val.trim().replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&/g, '&amp;');
var finalVal = this.val.trim();
if (finalVal.indexOf('<') !== -1 || finalVal.indexOf('>') !== -1 || finalVal.indexOf('&') !== -1) {
if (options && options.cdata) {
finalVal = "<![CDATA[" + finalVal + "]]>";
} else {
finalVal = escapeValue(finalVal);
}
}

if (options && options.trimmed && finalVal.length > 25)
finalVal = finalVal.substring(0,25).trim() + "…";
Expand Down