Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

xml

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.

like image 357
Tokendra Kumar Sahu Avatar asked Dec 01 '11 13:12

Tokendra Kumar Sahu


People also ask

How do I type Special Characters?

Inserting ASCII characters To insert an ASCII character, press and hold down ALT while typing the character code. For example, to insert the degree (º) symbol, press and hold down ALT while typing 0176 on the numeric keypad. You must use the numeric keypad to type the numbers, and not the keyboard.

How do I put special letters on my keyboard?

The US International Keyboard gives you two ways to add a special character: Use the right-hand Alt key in combination with the appropriate letter to get one of the more common combinations. For example, Alt+e will result in: é Press the symbol you want to use and then the letter you want to use it with.

How do you type Alt codes?

To use an Alt code, press and hold down the Alt key and type the code using the numeric key pad on the right side of your keyboard. If you do not have a numeric keypad, copy and paste the symbols from this page, or go back try another typing method.


1 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.

like image 119
maerics Avatar answered Oct 10 '22 11:10

maerics