如何在javascript中转义xml实体? [英] how to escape xml entities in javascript?

查看:135
本文介绍了如何在javascript中转义xml实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript(服务器端nodejs)中,我正在编写一个生成xml作为输出的程序。

In JavaScript (server side nodejs) I'm writing a program which generates xml as output.

我通过连接字符串来构建xml:

I am building the xml by concatenating a string:

str += '<' + key + '>';
str += value;
str += '</' + key + '>';

问题是:如果 value 包含该怎么办?字符如'&''>''<'
逃避这些角色的最佳方法是什么?

The problem is: What if value contains characters like '&', '>' or '<'? What's the best way to escape those characters?

或者是否有任何javascript库可以逃脱XML实体?

or is there any javascript library around which can escape XML entities?

推荐答案

HTML编码只是替换& '< > chars with他们的实体等价物。订单很重要,如果你不首先替换& 字符,你将对一些实体进行双重编码:

HTML encoding is simply replacing &, ", ', < and > chars with their entity equivalents. Order matters, if you don't replace the & chars first, you'll double encode some of the entities:

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;');
  };
}

As @Johan B.W. de Vries指出,这将有标签名称的问题,我想澄清我假设这是用于

相反,如果你想解码HTML实体 1 ,确保在其他所有内容之后将& amp; 解码为& 这样你就不会对任何实体进行双重解码:

Conversely if you want to decode HTML entities1, make sure you decode &amp; to & after everything else so that you don't double decode any entities:

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, '&');
  };
}

1 只是基础知识,不包括& copy; © 或其他此类事情

1 just the basics, not including &copy; to © or other such things

就图书馆而言。 Underscore.js (或 Lodash 您更喜欢)提供 _。escape 方法来执行此功能。

As far as libraries are concerned. Underscore.js (or Lodash if you prefer) provides an _.escape method to perform this functionality.

这篇关于如何在javascript中转义xml实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆