views:

45

answers:

2

I've been looking all over, and I can't find a clean solution (that I can make sense of).

How can I pull an entry at random from an xml list?

My starting point is as follows (which pulls the latest entry):

<script type="text/javascript">
 var xmlDoc=null;
 if (window.ActiveXObject)
 {// code for IE
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 }
 if (xmlDoc!=null)
 { 
  xmlDoc.async=false;xmlDoc.load("/folder/file.xml");
  var x=xmlDoc.getElementsByTagName("z:row");
  for (i=0;i<1;i++)
  {
   document.write(x[i].getElementsByTagName("@ows_Title")[0]
    .childNodes[0].nodeValue);
  }
 }
</script>

Any and all suggestions greatly welcomed!

A: 

Change the code slightly... to switch "for (i=0;i<1;i++)" with "var i = Math.floor((Math.random()*1000)%x.length);"

<script type="text/javascript">
 var xmlDoc=null;
 if (window.ActiveXObject)
 {// code for IE
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 }
 if (xmlDoc!=null)
 { 
  xmlDoc.async=false;xmlDoc.load("/folder/file.xml");
  var x=xmlDoc.getElementsByTagName("z:row");
  var i = Math.floor((Math.random()*1000)%x.length);
  {
   document.write(x[i].getElementsByTagName("@ows_Title")[0]
    .childNodes[0].nodeValue);
  }
 }
</script>

Cheers

RedGen
+1  A: 

Math.random() will return a number between 0 and 1, and getElementsByTagName returns a NodeList that has a length. Thus,

Math.floor(Math.random() * x.length)

gives you a random index into the NodeList. You can then use this index to call item() to get that node out of the list:

var nodeList = xmlDoc.getElementsByTagName("whatever");
var node = nodeList.item(Math.floor(Math.random() * nodeList.length));
Cameron Skinner