Jump to content

remove whitespace from XML file


karthikin

Recommended Posts

I have an xml file and I want to how can i remove the white-space in the xml file.For example this is my xml file:

<?xml version="1.0" encoding="UTF-8"?><CONTACTS><CONTACT><FirstName>SandfordFrankie</FirstName><LastName>Frankie Sandford</LastName><gmail/><yahoo/><URL>http://www.facebook.com/FrankieSandfordApprovedPage</URL><Facebook-ID/></CONTACT><CONTACT><FirstName>Julien </FirstName><LastName>Foder</LastName><gmail/><yahoo/><URL/><Facebook-ID/></CONTACT><CONTACT><FirstName>Stéphénè</FirstName><LastName>Rio</LastName><gmail/><yahoo>rio.sté1234@yahoo.com</yahoo><URL/><Facebook-ID/></CONTACT><CONTACT><FirstName>Aana</FirstName><LastName>Joséph</LastName><gmail></gmail><yahoo>aana.josé@yahoo.com</yahoo><URL></URL><Facebook-ID></Facebook-ID></CONTACT></CONTACTS>

If i delete a record and it'll be like this:

<?xml version="1.0" encoding="UTF-8"?><CONTACTS><CONTACT><FirstName>Julien </FirstName><LastName>Foder</LastName><gmail/><yahoo/><alcatel-lucent/><URL/><Facebook-ID/></CONTACT><CONTACT><FirstName>Stéphénè</FirstName><LastName>Rio</LastName><gmail/><yahoo>rio.sté1234@yahoo.com</yahoo><URL/><Facebook-ID/></CONTACT><CONTACT><FirstName>Aana</FirstName><LastName>Joséph</LastName><gmail></gmail><yahoo>aana.josé@yahoo.com</yahoo><URL></URL><Facebook-ID></Facebook-ID></CONTACT></CONTACTS>

When i delete a record from my xml file, how can i remove the white space from the file?Thanks guys.

Link to comment
Share on other sites

1. I can't help wondering why this matters to you.2. When you remove the node, you do not remove the whitespace that follows it. So that's the whitespace you see. To remove it, you will have to test the node type of the <CONTACT> node's nextSibling. If it is 3, remove it. You may need to do this before you remove the <CONTACT> node.3. If you want to remove ALL whitespace between in the document, this function should do it. You can pass it a single node or an entire DOM document.

function clearNode(myNode) {	var allNodes = myNode.childNodes;	var len = allNodes.length;	for (var i = len - 1; i >= 0; i--) {		if (allNodes[i].nodeType == 3) {			if (!allNodes[i].nodeValue.match(/\S/)) {				allNodes[i].parentNode.removeChild(allNodes[i]);			}		}		else if (allNodes[i].nodeType == 1) {			clearNode(allNodes[i]);		}	}	return myNode;}

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...