lunes, julio 17, 2006

Offspring matters ....

As you know, in XSD files, there is an attribute to mark an element as abstract. This means that other element will extend it. Typical example of Figure, with Circle, Square, ... as children.

Ok, that's perfect. Imagine you are using XmlBeans (XML binding). You have a list of FigureType, and want to iterate over all figures, and depending its type, make one thing or another (for example drawing the figure). In this case an instanceof approach won't work because in XML Beans we are working with interfaces, not with implementations object, so for example SquareType interface doesn't extends from FigureType interface. So how can we implements the previous example?

Using two thing, one working wiht DOM repesentation instead of object representation, and next using type attribute that all extentended tags require. An example:

<figure type="SquareType" area="c*c" sides="4">

Take a look that the tag is figure but square information is present.

Now let's see the java code to treat this example:

It is as simple as we can imagine:

First we return the DOM representation

final Node node = figureType.getDomNode();

Next we gets the type attribute using DOM library.

final NamedNodeMap nodeAttMap = node.getAttributes();

final String type = nodeAttMap.getNamedItemNS("", "type").getNodeValue();

Remember to change the first parameter of getNameItemNS if namespace of type attribute is changed.

and finally simply a hell if-then-else sequence:

if("SquareType".equals(type)) {

(SquareType) figureType.changeType(SquareType.type));

} else {

Take a look at line inside if; we must cast from FigureType to SquareType using changeType method.

And that's all, simple and easy, only tedious because of if-then-else chain.

Donate If You Can and Find Post Useful