在JavaScript(服务器端nodejs)中,我正在编写一个生成xml作为输出的程序.
我通过连接一个字符串来构建xml:
str += '<' + key + '>';
str += value;
str += '</' + key + '>';
Run Code Online (Sandbox Code Playgroud)
问题是:如果value包含像或等字符'&',该怎么办?逃避这些角色的最佳方法是什么?'>''<'
或者是否有任何javascript库可以逃脱XML实体?
zzz*_*Bov 105
HTML编码简单地更换&,",',<和>与他们的实体当量字符.订单很重要,如果你不&首先替换字符,你将对一些实体进行双重编码:
if (!String.prototype.encodeHTML) {
String.prototype.encodeHTML = function () {
return this.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
}
Run Code Online (Sandbox Code Playgroud)
正如@Johan BW de Vries指出的那样,标签名称会有问题,我想澄清一下,我假设这是唯一的用途value
相反,如果要解码HTML实体1,请确保在其他所有内容之后进行解码&,&以便不对任何实体进行双重解码:
if (!String.prototype.decodeHTML) {
String.prototype.decodeHTML = function () {
return this.replace(/'/g, "'")
.replace(/"/g, '"')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/&/g, '&');
};
}
Run Code Online (Sandbox Code Playgroud)
1只是基础知识,不包括©对©或其他类似的东西
就图书馆而言.Underscore.js(或Lodash如果你愿意)提供了一个_.escape执行此功能的方法.
hgo*_*ebl 95
对于相同的结果,这可能会更有效:
function escapeXml(unsafe) {
return unsafe.replace(/[<>&'"]/g, function (c) {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
}
});
}
Run Code Online (Sandbox Code Playgroud)
jpa*_*kal 20
如果你有jQuery,这是一个简单的解决方案:
String.prototype.htmlEscape = function() {
return $('<div/>').text(this.toString()).html();
};
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
"<foo&bar>".htmlEscape(); - > "<foo&bar>"
你可以使用以下方法.我在原型中添加了这个以便于访问.如果你把方法调用两次或更多,我也会使用负面预测,所以它不会弄乱.
用法:
var original = "Hi&there";
var escaped = original.EncodeXMLEscapeChars(); //Hi&there
Run Code Online (Sandbox Code Playgroud)
在XML解析器中自动解码解码.
方法 :
//String Extenstion to format string for xml content.
//Replces xml escape chracters to their equivalent html notation.
String.prototype.EncodeXMLEscapeChars = function () {
var OutPut = this;
if ($.trim(OutPut) != "") {
OutPut = OutPut.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
OutPut = OutPut.replace(/&(?!(amp;)|(lt;)|(gt;)|(quot;)|(#39;)|(apos;))/g, "&");
OutPut = OutPut.replace(/([^\\])((\\\\)*)\\(?![\\/{])/g, "$1\\\\$2"); //replaces odd backslash(\\) with even.
}
else {
OutPut = "";
}
return OutPut;
};
Run Code Online (Sandbox Code Playgroud)