I’m looking for a function to convert a string to the xml string with xml entities where needed. Something like htmlentities in PHP but for XML and in Javascript.
Thank you for any help!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s nothing built-in (except
innerHTMLserialisation which is super-dodgy for this purpose), you’d have to write it yourself, eg.:This is a maximalist escaping function for safety:
it will always encode
",'and tab/CR/LF characters though they only need to be escaped in an attribute value, where that particular quote character is being used as a delimiter.it will always encode
>though this only actually needs to be escaped when part of the]]>sequence in text content.If you don’t need these properties you can remove the
replaces you don’t need (it’s pretty rare to need to put tab/CR/LF in an attribute value, for example).If you need to produce HTML-compatible XHTML, use
'instead of'if you need that escape.In general you should avoid
htmlentitiesand usehtmlspecialcharsinstead, ashtmlentitiesunnecessarily encodes all non-ASCII characters as HTML entity references, which also has the side-effect of screwing up your text if you don’t give it the right$charsetparameter.