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("http://www.w3.org/2001/XMLSchema-instance", "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.

1 comentarios:

Wulan Dari dijo...

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game. Both boys and girls feel the impact of just a moment’s pleasure, for the rest of their lives.

Click Here
Visit Web
Swiatkarpia.com
Information