javascript 如何使用jQuery转义或替换xml文件中的“&”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9164164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape or replace "&" in xml file using jQuery?
提问by manraj82
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?
我有一个 xml 文件,它可能会在进程中插入 5 个特殊字符,如“&”。我知道 xml 在解析这些字符时会抛出错误。我使用 jQuery ajax 方法从 xml 文件中获取数据。有吗有什么方法可以克服 javascript 中的这个解析器错误,比如替换特殊字符?
回答by Mala
In short, yes, assuming you get your xml as a string (which if I recall correctly, jQuery does). Then you can do the following:
简而言之,是的,假设您将 xml 作为字符串(如果我没记错的话,jQuery 确实如此)。然后您可以执行以下操作:
xmlstr = xmlstr.replace(/&/g, "&");
for any characters you want to replace.
对于要替换的任何字符。
回答by Daniel Moses
Let's say a user inputs this:
假设用户输入:
<foo> >bar< hi & bye >/bar<
Now, they likely meant:
现在,他们可能的意思是:
<foo> >bar< hi & bye >/bar< </foo>
But they could have meant:
但他们的意思可能是:
<foo> &gt;bar&lt; hi & bye &gt;/bar&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.
您可以通过关闭未关闭的标签和转义 & 来清理和清理应该是格式良好的 XML 的文本。我不熟悉任何可以为您执行此操作的 javascript 库。
回答by A Ghazal
XMLText = XMLText.Replace("&", "&");
XMLText = XMLText.Replace("""", """);
XMLText = XMLText.Replace("'", "'");
XMLText = XMLText.Replace("<", "<");
XMLText = XMLText.Replace(">", ">");
return XMLText;