|
|
I have written a very simple javascript function to do the job. The function takes a Javascript string (or any value, integer etc.) as input, converts it into a string and then replaces all occurrences of <, >, &, ", and ' with their html values. Please note that on the server side e.g. in PHP, ASP you have to decode the xml values to process them properly. I have also written the PHP function, which is described here.
|
function xml_encode(input)
{
if(input == undefined)
{
alert("error in xml_encode: input undefined");
return;
}
input = trim(input.toString());
var replace_with = '&';
// The 'g' in the first argument is used to tell the function 'replace'
// that all occurences (g = global)
// of the character in between slashes have to be replaced.
input = input.replace(/&/g, replace_with);
replace_with = '<';
input = input.replace(/</g, replace_with);
replace_with = '>';
input = input.replace(/>/g, replace_with);
replace_with = ''';
input = input.replace(/'/g, replace_with);
replace_with = '"';
input = input.replace(/"/g, replace_with);
return input;
}
Using xml_encode() - A simple example (JavaScript Code):
So, now let's say you want to create an XML string manually (in JavaScript) you'll use the function as follows:
var xml = "<?xml version='1.0' standalone='yes'?>";
name_variable = trim(document.getElementById('your_name').value);
xml += "<name>";
xml += xml_encode(name_variable);
xml += "</name>";
The trim function used in the example above is defined here.
=======================================================================================
Support Techs Worldwide:Link to us:
You can support us by putting a link to our website on your blog or website (code is below).
<a href="http://www.techsww.com">
Techs Worldwide - Tutorials about Software Installation,
Configuration, Administration, Monitoring, Tools, Tips &
Tricks
</a>
OR a simple one.
<a href="http://www.techsww.com">
Techs Worldwide - IT related Tutorials
</a>
Feedbacks: We appreciate feedbacks and suggestions about our tutorials and Techs Worldwide from readers. Please contact us using the form here and let us know what you think about the tutorial and the website in general.
Bookmark Us:
We are working on new features for the website, please keep visiting or bookmark us using your favourite bookmarking service.
Subscribe to RSS:
You can subscribe to our RSS feed here.
|