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


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.