Use Unique Element Names in your XML

The Problem

It seems to me that this should be fairly obvious, but you should use unique element names in your XML. I only bring this up because I recently ran into some XML code at work that breaks this guideline. Here is an example of what I’m talking about (Keep in mind that this is valid XML and there is no rule that states that the names must be unique):



  
    Windows
    XP
  
  
    Ubuntu
    Hardy Heron
  

Now, let’s say that we have some javascript code where we want to grab an array of all of the top-level os elements. There are a number of ways we could do this, such as using X-Path or using getElementsByTagName as in the following code snippet:

var xmlDoc = loadXMLDoc("oss.xml");
var oss = xmlDoc.getElementsByTagName('os');
var numNodes = oss.length;
for(var i=0; i < numNodes; i++)
{
    var node = oss[i];
    alert(node.text);
}
return false;

However, with the current XML the above code snippet grabs all 4 nodes that have an element name of os. In most cases this is not what we would actually want. Instead, we would usually only want the top-level os nodes so that we can loop over them.

Rewrite the XML

By changing the inner node name to os_name, we get the desired behavior of only grabbing the 2 nodes named os when we use getElementsByTagName.



  
    Windows
    XP
  
  
    Ubuntu
    Hardy Heron
  

Leave a Reply