如何在javascript中转义xml实体?

Zo7*_*o72 72 javascript

在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, '&amp;')
               .replace(/</g, '&lt;')
               .replace(/>/g, '&gt;')
               .replace(/"/g, '&quot;')
               .replace(/'/g, '&apos;');
  };
}
Run Code Online (Sandbox Code Playgroud)

正如@Johan BW de Vries指出的那样,标签名称会有问题,我想澄清一下,我假设这是唯一的用途value

相反,如果要解码HTML实体1,请确保在其他所有内容之后进行解码&amp;,&以便不对任何实体进行双重解码:

if (!String.prototype.decodeHTML) {
  String.prototype.decodeHTML = function () {
    return this.replace(/&apos;/g, "'")
               .replace(/&quot;/g, '"')
               .replace(/&gt;/g, '>')
               .replace(/&lt;/g, '<')
               .replace(/&amp;/g, '&');
  };
}
Run Code Online (Sandbox Code Playgroud)

1只是基础知识,不包括&copy;©或其他类似的东西


就图书馆而言.Underscore.js(或Lodash如果你愿意)提供了一个_.escape执行此功能的方法.

  • 我知道这个答案是陈旧的,但只是为JS的新手说清楚:将一些标准化提案的非填充的随机函数附加到全局原型是一个坏主意. (3认同)
  • 这几乎涵盖了5个XML实体.只需要@apos; (2认同)
  • 这看起来像是一遍又一遍地替换相同的字符串,这在处理大量数据时可能会很重要.有更快的选择吗? (2认同)
  • @Jonny,正则表达式将提供比对`.replace()`的多次调用更差的性能.在任何一种情况下,您都必须拥有大量数据才能发现任何重大问题.更快的替代方案是对应用程序进行基准测试并找到*实际*阻塞点(通常是嵌套循环),而不是担心这样的事情可以忽略不计. (2认同)

hgo*_*ebl 95

对于相同的结果,这可能会更有效:

function escapeXml(unsafe) {
    return unsafe.replace(/[<>&'"]/g, function (c) {
        switch (c) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            case '\'': return '&apos;';
            case '"': return '&quot;';
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

  • @VictorGrazi:你的权利,它在 50 次测试中的 49 次中是更快的解决方案。也许是因为它比公认的答案年轻近 5 岁。 (2认同)

jpa*_*kal 20

如果你有jQuery,这是一个简单的解决方案:

  String.prototype.htmlEscape = function() {
    return $('<div/>').text(this.toString()).html();
  };
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

"<foo&bar>".htmlEscape(); - > "&lt;foo&amp;bar&gt"

  • 单引号和双引号一般不需要转义。 (2认同)

sud*_*u63 6

你可以使用以下方法.我在原型中添加了这个以便于访问.如果你把方法调用两次或更多,我也会使用负面预测,所以它不会弄乱.

用法:

 var original = "Hi&there";
 var escaped = original.EncodeXMLEscapeChars();  //Hi&amp;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, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
        OutPut = OutPut.replace(/&(?!(amp;)|(lt;)|(gt;)|(quot;)|(#39;)|(apos;))/g, "&amp;");
        OutPut = OutPut.replace(/([^\\])((\\\\)*)\\(?![\\/{])/g, "$1\\\\$2");  //replaces odd backslash(\\) with even.
    }
    else {
        OutPut = "";
    }
    return OutPut;
};
Run Code Online (Sandbox Code Playgroud)

  • 未经充分认可的优秀解决方案.确保你不会与臭名昭着的&amp; amp; 输出中的字符串很漂亮. (2认同)