JDOM2 Feature Content.CType

rolfl edited this page Apr 8, 2012 · 2 revisions

A lot of JDOM processing relies on scanning sets of JDOMContent for certain types of data. This has traditionally been done using the instanceof operator. JDOM2 introduces the Content.CType enum which allows the type-checking to be done using the Enumeration process rather than instanceof. Additionally, this makes it possible to process Collections of content using a switch statement:

  for (Content c : element.getContent()) {
     switch (c.getCType()) {
         case Element :
               ... // do something with Element content
               break;
         .....
     }
  }

One very important observation about JDOM is that the CDATA class is a sub-class of the Text class. This relationship is often forgotten, and can lead to numerous bugs. On the other hand, the relationship between them can be taken advantage of too. From the perspective of the Content.CType though, CType.CDATA and CType.Text are exclusive. In other words, the following two statements are not the same:

if (c instanceof Text) {
    // true for Text and CDATA
}

or

if (c.getCType() == CType.Text) {
    // true for Text content only.
}

You can take advantage of these differences if you know about them!