1

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?

manraj82
  • 5,929
  • 24
  • 56
  • 83
  • http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery seems to have your answer. – deltree Feb 06 '12 at 17:16
  • 1
    Are you saying the server is returning malformed XML? If so, you'll want to fix it at the server. If not, I don't understand the question – Daniel Moses Feb 06 '12 at 17:17
  • @DMoses i know this is going to sound too dumb,and i should not even be asking these sort of questions.The server is not returning the malformed XML,its user input from notpad.Is it possible to fix the malformed XML in javascript? I know the answer is going to be NO,just wanted to check if there was a solution. – manraj82 Feb 06 '12 at 17:24
  • I know this might be too late, but you would need to parse your xml for special characters. One way is to use php (if you file comes from php) like this: `preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string)` or like the guy down below suggested with javascript: `xmlstr = xmlstr.replace(/&/g, "&");` – Henrique Donati Sep 29 '16 at 00:22

3 Answers3

2

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.

Mala
  • 14,178
  • 25
  • 88
  • 119
1

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.

Daniel Moses
  • 5,872
  • 26
  • 39
0
XMLText = XMLText.Replace("&", "&amp;");
XMLText = XMLText.Replace("""", "&quot;");
XMLText = XMLText.Replace("'", "&apos;");
XMLText = XMLText.Replace("<", "&lt;");
XMLText = XMLText.Replace(">", "&gt;");
return XMLText;
A Ghazal
  • 2,693
  • 1
  • 19
  • 12