Jump to content

Parse XML


mikhl

Recommended Posts

Hi. I have some XML that is allways formatted like the snippet below. i am trying to parse it with a JS function but I am having no success what so ever.

 

<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
<offer>
	<bookTitle>Book Title</bookTitle>
	<catDesc>Category</catDesc>
	<bookPrice>£29.99</bookPrice>
</offer>
</root>

 

The JS I have to do this so far is below and I dont think it works very well at all. I seem to be able to get the first element (the title of the book) with the .firstChild function. But I cant access the others. I was also trying something with .nextSibling but having no luck there either.

 

function displayXML( data ){
   var root = data.documentElement; // get root element
   var nElements = root.childNodes.length;
   var retval = "";

   alert(nElements);

   var offer = root.childNodes;
   nOfferElems = offer.length;

   alert(nOfferElems);
   for(var j = 0; j < nElements; j++){
   
   		if(root.childNodes[j].hasChildNodes()){

	   for ( var n = 0; n < nOfferElems; n++) {
	   		
	      if (offer[j].childNodes[n].hasChildNodes()) {
	      	
	         var node = offer[j].childNodes[n];
	         retval += node.firstChild.nodeValue;
	         
	         for(var i = 0; i < nOfferElems; i++){
	         	alert('test - ' + (i+1));
	         	alert('nodeType: ' + node.childNodes[i].nodeType);
	         	if(node.childNodes[i].nodeType != 4){
	         		alert('node test - ' + (i+1));
		         	alert(node.childNodes[i].nodeValue);
		         	//node = node.nextSibling;
	         	}
	         }

	         retval += "<br />\n";
	      }
	   }//end for
	}//end if
   }//end for
   // the id of the element on the receiving html page
   // where the output will be displayed
   document.getElementById('special2').innerHTML = retval;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.