Tucker
Tucker

Reputation: 13

Java DOM parser cast error

Ok, so this is a simple decision tree, breadth and depth first search program. In my print tree method, im using the same element casting process as in my search methods, i get no errors when i run the print tree method on its own, when i uncomment my search methods, i get an exception in main and a cannot cast exception in both the depth first and breadth first methods but the tree still prints. The exception comes specifically from the cast line after i get the root children in the methods. i need new eyes for this one, im brand new to using xml in java anyway so im pulling my hair out.

xml: (comment says that im incorrectly assuming that all child nodes are elements, i actually was assuming that all nodes were nodes, not elements and that they could be cast to elements, sorry)

<root>
 <node behavior="Idle" response="">
      <node behavior="" response="Use Computer"/>
      <node behavior="" response="Patrol"/>
 </node>
 <node behavior="Incoming Projectile">
      <node behavior="" response="Evade"/>
 </node>
 <node behavior="Combat" response="">
      <node behavior="Melee" response="">
           <node behavior="" response="Flee"/>
           <node behavior="" response="Attack"/>
      </node>
      <node behavior="Ranged" response="">
           <node behavior="" response="Weapon 1"/>
           <node behavior="" response="Weapon 2"/>
           <node behavior="" response="Weapon 3"/>
      </node>
 </node>
</root>

This is the output from the program when i run print tree with the searches, like i said if i dont run the searches with it i dont get that first exception:

Specify BehaviorIdle
behavior= Idle
Exception in thread "main"      response= Use Computer
        response= Patrol
behavior= Incoming Projectile
        response= Evade
behavior= Combat
    behavior= Melee
        response= Flee
        response= Attack
    behavior= Ranged
        response= Weapon 1
        response= Weapon 2
        response= Weapon 3
java.lang.ClassCastException:com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element
at XmlTree.breadthFirst(XmlTree.java:58)
at decisiontree.main(decisiontree.java:34)

Main:

import java.util.*;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class decisiontree {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    ArrayList <org.w3c.dom.Node> queue = new ArrayList<org.w3c.dom.Node>();
    int dCounter = 0;
    int bCounter = 0;

    System.out.print("Type in path for xml file: ");
    String path = scan.nextLine();

    System.out.print("Specify Behavior");
    String target = scan.nextLine();

    scan.close();


    XmlTree dTree = new XmlTree();
    Document doc =dTree.xmlIn(path);


    NodeList thisList = doc.getElementsByTagName("root");
    Node root = thisList.item(0);

    dTree.printTree(doc);

    String dResponse = dTree.depthFirst(root, target, dCounter);
    String bResponse = dTree.breadthFirst(root, queue, target, bCounter);

    System.out.println("Behavior: "+ target +"\n"+"Depth First Response: " + dResponse +
                         "\n" + "Breadth First Response: "+ bResponse + "\n" + "Depth First Took "+
                        dCounter + " jumps"+"\n"+"Breadth First Took "+ bCounter +" jumps");

    }

}

Print Tree:

public void printTree(Document doc){

    NodeList rootList = doc.getElementsByTagName("root");
    org.w3c.dom.Node root = rootList.item(0);
    Element rootElement = (Element) root;
    NodeList nodeList = rootElement.getElementsByTagName("node");

    for(int i = 0; i < nodeList.getLength(); i++){
        org.w3c.dom.Node nodes = nodeList.item(i);
        Element nodeElement = (Element) nodes;
        if(nodeElement.getAttribute("behavior") != ""){
            if(nodeElement.getParentNode() != rootElement){
                System.out.println("    behavior= " + nodeElement.getAttribute("behavior"));
            }else{
                System.out.println("behavior= " + nodeElement.getAttribute("behavior"));
            }
        }else if(nodeElement.getAttribute("behavior") == ""){
            if(nodeElement.getParentNode() != rootElement.getChildNodes()){
                System.out.println("        response= " + nodeElement.getAttribute("response"));
            }else{
                System.out.println("    response= " + nodeElement.getAttribute("response"));
            }
        }
    }
}

Depth First:

public String depthFirst(org.w3c.dom.Node root, String target, int dCounter){

    if (root.getChildNodes() == null){
        return "no tree";
    }
    dCounter++;
    NodeList nL = root.getChildNodes(); 
    for(int i = 0;i < nL.getLength();i++){
        org.w3c.dom.Node node = nL.item(i); 
        Element nodeElement = (Element) node;   //ERROR ON THIS LINE
        if(nodeElement.getAttribute("behavior") == target){
            while(nodeElement.hasChildNodes()){
                NodeList newNL = nodeElement.getChildNodes();
                Random rand = new Random();
                int x = rand.nextInt(newNL.getLength());
                node = newNL.item(x);
                Element newElement = (Element) node;
                nodeElement = newElement;
                dCounter++;
            }
        String response = nodeElement.getAttribute("response");
        return response;
        }else{
            depthFirst(node, target, dCounter);
        }
    }

    return null;
}

Breadth First:

public String breadthFirst(Node root, ArrayList<org.w3c.dom.Node> q, String target, int bCounter){

    if(!root.hasChildNodes()){
        return "no tree";
    }
    bCounter++;
    NodeList nL = root.getChildNodes();
    for(int i = 0; i < nL.getLength(); i++){
        q.add(nL.item(i));
    }
    Node node = q.get(0);
    Element nodeElement = (Element) node;   // ERROR ON THIS LINE

    if(nodeElement.getAttribute("behavior") != target){
        q.remove(0);
        Node newNode = q.get(0);
        Element newElement = (Element) newNode;
        breadthFirst(newElement, q, target, bCounter);
    }
    if(nodeElement.getAttribute("behavior") == target){
        while(nodeElement.hasChildNodes()){
            NodeList newNL = node.getChildNodes();
            Random rand = new Random();
            int x = rand.nextInt(newNL.getLength());
            Element newElement = (Element) newNL.item(x);;
            nodeElement = newElement;
            bCounter++;
        }
    String response = nodeElement.getAttribute("response");
    return response;
    }
    return null;
}

Upvotes: 1

Views: 1811

Answers (1)

VGR
VGR

Reputation: 44404

Looking at the first two lines of your XML:

<root>
 <node behavior="Idle" response="">

It would appear that the first child Node of <root> is a <node> element, but that is not the case.

The first child is actually a Text object, whose character content is "\n " (or possibly "\r\n ", depending on which platform’s line endings the XML document uses), representing the text between the opening <root> tag and the beginning of the first <node> tag. The second child is the <node> Element.

The simplest fix for this is to do an if (nodes instanceof Element) check before proceeding. If you are familiar with XPath, I would use that instead, as the code will be cleaner.

Caution: Comparing strings using == and != will eventually fail. In Java, you must use a method call to compare String objects. You need to replace this:

nodeElement.getAttribute("behavior") == ""

with this:

nodeElement.getAttribute("behavior").isEmpty()

And similarly, you need to replace this:

nodeElement.getAttribute("behavior") != ""

with this:

!nodeElement.getAttribute("behavior").isEmpty()

In general, if you want to compare Strings to any value other than the empty string, you need to use the equals method. For instance:

nodeElement.getAttribute("behavior").equals(target)

Upvotes: 1

Related Questions