Deserializing and Reserializing XML in JavaScript

The JavaScript code below, when run, displays an XML-formatted text string, deserializes it into an an XMLDocument object, re-serializes that object into another text string, and then displays that text string. To see it in action, copy it into an .html file and open that file in a web browser that runs JavaScript.

XMLSerialization


<html>
<body>
<script type="text/javascript">

function main()
{
	var xmlStringToParse = 
		"<artist name='The Jimi Hendrix Experience'>"
		+ " <albums>"
		+ "  <album name='Are You Experienced?' year='1967'></album>"
		+ "  <album name='Axis: Bold as Love' year='1967'></album>"
		+ "  <album name='Electric Ladyland' year='1968'></album>"
		+ " </albums>"
		+ "</artist>";

	document.write("XML before parsing:<br/><br/>");
	document.write(escapeStringForHTML(xmlStringToParse));
	document.write("<br/><br/>");

	var parser = new DOMParser();
	var xmlDocument = parser.parseFromString
	(
		xmlStringToParse, "text/xml"
	);

	var serializer = new XMLSerializer();
	var xmlStringReserialized = serializer.serializeToString(xmlDocument);
	document.write("XML after reserialization:<br/><br/>");
	document.write(escapeStringForHTML(xmlStringReserialized));
}

function escapeStringForHTML(valueToEscape)
{
	return valueToEscape.replace
	(
		/</g, "&lt;"
	).replace
	(
		/>/g, "&gt;"
	);
}

main();

</script>
</body>
</html>

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s