Looking for XML elements in Javascript with e4x

If you are manipulating XML in Javascript then E4X is one of the options available to you. The problem is that the documentation is a little thin and the examples only show you how to find things that definitely exist. So here’s some help in trying to see if elements exist or not.

In this example, I’m processing DITA and trying to find the “title” of the document. This can be in a variety of locations in DITA and can be a <title> in a topic, concept, etc. or a <mainbooktitle> element in a bookmap. So how do you see if you have a mainbooktitle in e4x?

var concept = new XML("...my dita concept xml...");
var mainbooktitle = concept..mainbooktitle;
if (mainbooktitle.length() > 0) {
    // we have a mainbooktitle

The concept..mainbooktitle construct finds all children elements in the document named mainbooktitle and returns them in an XMLList. Crucially the documentation does not tell you that an XMLList is always returned and can either be:

  1. A list of length zero meaning no elements named mainbooktitle were found
  2. A list of length one meaning only one element was found. When this happens, you can refer to the item as if it were not in a list. For example, to get the id attribute you could just say mainbooktitle.@id instead of mainbooktitle[0].@id.
  3. A list of length greater than one. You should then use a for each loop or access items by index like this mainbooktitle[1].@id

I hope this saves somebody some time because I had to figure it out by trial and error!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s