manraj82
manraj82

Reputation: 6305

How to escape or replace "&" in xml file using jQuery?

I have got a xml file that might get the 5 special characters like "&" inserted during a process.I know xml will throw error while parsing these characters.Im using the jQuery ajax method to get the data from the xml file.Is there any way of overcoming this parser error in javascript like replacing the special characters?

Upvotes: 1

Views: 16125

Answers (3)

A Ghazal
A Ghazal

Reputation: 2823

XMLText = XMLText.Replace("&", "&");
XMLText = XMLText.Replace("""", """);
XMLText = XMLText.Replace("'", "'");
XMLText = XMLText.Replace("<", "&lt;");
XMLText = XMLText.Replace(">", "&gt;");
return XMLText;

Upvotes: 0

Daniel Moses
Daniel Moses

Reputation: 5858

Let's say a user inputs this:

<foo> &gt;bar&lt; hi & bye &gt;/bar&lt;

Now, they likely meant:

<foo> &gt;bar&lt; hi &amp; bye &gt;/bar&lt; </foo>

But they could have meant:

<foo> &amp;gt;bar&amp;lt; hi &amp; bye &amp;gt;/bar&amp;lt; </foo>

You can clean up and sanitize text that should be well formed XML by closing unclosed tags and escaping &s. I'm not familiar with any javascript library that will do this for you.

Upvotes: 1

Mala
Mala

Reputation: 14843

In short, yes, assuming you get your xml as a string (which if I recall correctly, jQuery does). Then you can do the following:

xmlstr = xmlstr.replace(/&/g, "&amp;");

for any characters you want to replace.

Upvotes: 2

Related Questions