Checking folder content

I have a gallery that I built using xml for all the images like a typical xml gallery, Preloaders, thumbnails etc…
Gallery works perfectly, all the images and thumbs preload and everything is pulled via xml.
E.g.
<gallery>
<galleryPic location=“gallery/galleryImage_001.jpg”/>
<galleryPic location=“gallery/galleryImage_002.jpg”/>
<galleryPic location=“gallery/galleryImage_003.jpg”/>

              Etc…

</gallery>
I am trying to figure how I can set the xml to load 50 images as a standard and never have to physically alter the xml (so I can use it as a universal gallery without having to update the xml every 5min)
The problem with that is my code adds the containers for all 50 images, and I don’t want that to happen.
I would like the code to automatically load the pics which are in the folder even if there are less than 50 images and remove all empty containers.
So then if I drop 10, 20, 37 images as I choose it will load the correct amount without having to change the xml plus have no empty containers.