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

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

I tried replacing some special characters, for example:

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

For instance:

 <category label='ARR Builders & Developers'> 

Thanks.

+6
source share
3 answers

Consider creating XML using DOM methods . For instance:

 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 crowding out XML objects, but may have some cross-browser issues.

+3
source

This will make a replacement in JavaScript:

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

It uses regular expression literals to replace less and more characters with their equivalent equivalent.

+2
source

JavaScript comes with a powerful replace() method for string objects.

In general - and basic - terms, it works as follows:

 var myString = yourString.replace([regular expression or simple string], [replacement string]); 

The first argument to the .replace() method is the part of the original string that you want to replace. It can be represented either by a simple string object (even a literal), or by a regular expression.

Regular expression is obviously the most powerful way to select a substring.

The second argument is a string object (even a literal) that you want to provide as a replacement.

In your case, the replacement operation should look like this:

 xmlData=xmlData.replace(/&/g,"&amp;"); xmlData=xmlData.replace(/>/g,"&gt;"); //this time it should work. 

Note that the first replacement operation is an ampersand, as if you tried to replace it later, you would probably veil existing well-cited objects in exactly the same way as "&amp;gt;" .

Also, pay attention to the regular expression 'g' flag, since with it the replacement will take place throughout the text, and not just the first match.

I used regular expressions, but for simple replacements like these, simple strings would be ideal.

You can find the full link for String.replace() here .

+1
source

Source: https://habr.com/ru/post/902839/


All Articles