views:

262

answers:

2

Hey everyone,

I'm getting an IllegalCastException on the following (see bold line):

public void renderXML(final String xml) {
 final Document xmlDoc = XMLParser.parse(xml);
 final com.google.gwt.xml.client.Element root = xmlDoc.getDocumentElement();
 XMLParser.removeWhitespace(xmlDoc);

 final NodeList collection = root.getElementsByTagName("collection");
   for (int i = 0; i < collection.getLength(); i++) {
     **final Element coll= (Element)collection.item(i);**
     RootPanel.get("slot2").add(new Label("coll: "));
   }
}

Does anyone know why this is so? I've looked at examples, and it seems that this is supposed to be how to do it. I am using the following related imports:

 import com.google.gwt.xml.client.Document;
 import com.google.gwt.xml.client.NodeList;
 import com.google.gwt.xml.client.XMLParser;

One thing to make note of here...Element is imported as "import com.google.gwt.dom.client.Element;", I cannot import "import com.google.gwt.xml.client.XMLParser;" as it will give me the error:

"The import com.google.gwt.xml.client.Element collides with another import statement"

Any suggestions? Thanks!

+1  A: 

Did you try to import directly into the source code instead of declaring at the import lines?

public void renderXML(final String xml) {
        // just directly import it as local variable. 
        final Document xmlDoc = com.google.gwt.xml.client.XMLParser.XMLParser.parse(xml);
        final com.google.gwt.xml.client.Element root = xmlDoc.getDocumentElement();
        XMLParser.removeWhitespace(xmlDoc);

        final NodeList collection = root.getElementsByTagName("collection");
          for (int i = 0; i < collection.getLength(); i++) {
            **final Element coll= (Element)collection.item(i);**
            RootPanel.get("slot2").add(new Label("coll: "));
          }
}

I hope it helps.

Tiger

Tiger
Tiger, that worked. Thanks for your help!
behrk2
+2  A: 

The method com.google.gwt.xml.client.NodeList.item returns a com.google.gwt.xml.client.Node, not com.google.gwt.xml.client.Element. Such a Node might be an Element, but there is no guarantee. You must check the type of the item that is returned before casting it.

Also, you must use the appropriate Element; you can't substitute one for the other. You must either avoid importing the other Element, or fully specify the Element you need here.

For instance, assuming in your code you only care about Element, and you don't eliminate the other import, then you can change your loop to be as such:

final NodeList collection = root.getElementsByTagName("collection");
for (int i = 0; i < collection.getLength(); i++) {

    Node node = collection.item(i);
    if (!(node instanceof com.google.gwt.xml.client.Element)) {
        continue;
    }

    com.google.gwt.xml.client.Element coll =
    (com.google.gwt.xml.client.Element)node;
    RootPanel.get("slot2").add(new Label("coll: "));
}
Jared Oberhaus
That did the tricks, thanks!
behrk2