How to add special characters like & > in XML file using JavaScript

I am generating XML using Javascript. It works fine if there are no special characters in the XML. Otherwise, it will generate this message: "invalid xml".

I tried to replace some special characters, like:

xmlData=xmlData.replaceAll(">",">");
xmlData=xmlData.replaceAll("&","&");
//but it doesn't work.

For example:

<category label='ARR Builders & Developers'>

Thanks.

Answers


Consider generating the XML using DOM methods. For example:

var c = document.createElement("category");
c.setAttribute("label", "ARR Builders & Developers");
var s = new XMLSerializer().serializeToString(c);
s; // => "<category label=\"ARR Builder &amp; Developers\"></category>"

This strategy should avoid the XML entity escaping problems you mention but might have some cross-browser issues.


This will do the replacement in JavaScript:

xml = xml.replace(/</g, "&lt;");
xml = xml.replace(/>/g, "&gt;");

This uses regular expression literals to replace all less than and greater than symbols with their escaped equivalent.


Need Your Help