如何解析带有特殊字符的xml?专门用于&符号

sug*_*nya 3 javascript xml special-characters

我从文本框中获取数据并将其更改为 xml 格式并将其存储在数据库中。为了允许特殊字符,我编写了 javascript 函数来用它的 html 实体替换特殊字符。

 "     "
 &     &
 <     &lt;
 >     &gt;
Run Code Online (Sandbox Code Playgroud)

对于“引号,小于,大于”其工作正常。对于“&”,它显示了 xml 解析器错误,我使用 javascript 用它的实体替换了特殊字符

  string.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, "\\'");

  for "&" allow showing warning but it get stored in data base. please help me to sort out this problem . 


 i begin with string.replace(/&/g, '&amp;') even though i am getting 
Run Code Online (Sandbox Code Playgroud)

警告:SimpleXMLElement::__construct():实体:第 9 行:解析器错误:EntityRef:期望 ';' 在 /var/www/ 我也试过这个 &amp; 正如此链接中提到的stackoverflow.com/questions/1328538/...
之后没有警告,但在保存在 db 中时,它保存为“ab & cd”

Koo*_*Inc 5

替换&字符开始然后替换其他字符。否则,您将从&以前的实体(&lt;等)替换为&amp;

string.replace(/&/g, '&amp;amp;') //<= start with
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&apos');
// &apos; may be "\\'",  depends on how te OP wants to use it
Run Code Online (Sandbox Code Playgroud)

[根据评论编辑] 用于&amp;amp;替换与字符