JCquence
JCquence

Reputation: 21

Android XML: Can't cast node to element

I'm trying to read a xml file, but it keeps telling me: java.lang.ClassCastException: org.apache.harmony.xml.dom.ElementImpl cannot be cast to android.renderscript.Element

Why can't i cast nNode to an Element?

    import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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

import android.renderscript.Element;
import android.util.Log;

class XMLParser
{
    public void read(File f)
    {
        try {

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(f);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("staff");

            Log.i("xml", "xml: start");
            Log.i("xml", "xml: root = "+ doc.getDocumentElement().getNodeName());

            for (int temp = 0; temp < nList.getLength(); temp++)
            {
                Node nNode = nList.item(temp);
               //Element eElement = (Element) nList.item(temp);

               if(nNode.getNodeType() == Node.ELEMENT_NODE)
               {
                  Element eElement = (Element) nNode;

                  Log.i("xml", "xml: photo "+ getTagValue("firstname", eElement));

               }
            }
          } catch (Exception e) {
            Log.i("xml", "xml: doet niet " + e.toString());
          }
    }

    private static String getTagValue(String sTag, Element eElement)
    {
        NodeList nlList = ((Document) eElement).getElementsByTagName(sTag).item(0).getChildNodes();

        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
    }
}

XML file:

<?xml version="1.0" encoding="UTF-8"?>
<company>
<staff>
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>100000</salary>
</staff>
<staff>
    <firstname>low</firstname>
    <lastname>yin fong</lastname>
    <nickname>fong fong</nickname>
    <salary>200000</salary>
</staff>
</company>

Upvotes: 2

Views: 5074

Answers (2)

Bourbon
Bourbon

Reputation: 1065

You are importing the wrong thing:

Replace: import android.renderscript.Element;

with this: import org.w3c.dom.Element;

Then proceed with this:

If you use DOMParser, here is some helping methods :

private String getNodeValueByTagName(Node parentNode, String tagNameOfNode)
{
    String nodeValue = "";
    if (((Element) parentNode).getElementsByTagName(tagNameOfNode).getLength() != 0)
        if (((Element) ((Element) parentNode).getElementsByTagName(tagNameOfNode).item(0)).hasChildNodes())
        {
            nodeValue = ((Node) ((Element) ((Element) parentNode).getElementsByTagName(tagNameOfNode).item(0)).getChildNodes().item(0)).getNodeValue();
        }
    return nodeValue;
}

private String getNodeAttributeByTagName(Node parentNode, String tagNameOfAttr)
{
    String nodeValue = "";

    NamedNodeMap questNodeAttr = parentNode.getAttributes();

    if (questNodeAttr.getLength() != 0)
        nodeValue = questNodeAttr.getNamedItem(tagNameOfAttr).getTextContent();

    return nodeValue;
}

Then in your example :

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setCoalescing(true); //If you use CDATA in your nodes
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(f);
        doc.getDocumentElement().normalize();

        NodeList staffNodeList = doc.getElementsByTagName("staff");

        for (int i = 0; i < staffNodeList.getLength(); i++)
        {
            Node staffNode = staffNodeList.item(i);
            String firstNameString = getNodeValueByTagName(staffNode, "firstname");
            String lastNameString = getNodeValueByTagName(staffNode, "lastname");
            String nickNameString = getNodeValueByTagName(staffNode, "nickname");
            String salaryString = getNodeValueByTagName(staffNode, "salary");
            int salaryInt = (salaryString.equals(""))?0:Integer.parseInt(salaryString);
            // TODO : Place your code here!
        }

Upvotes: 9

Basbous
Basbous

Reputation: 3925

Try to use the XML Parser like this

public void vParseXML(String sXMLResult)
    {   
        org.xml.sax.helpers.DefaultHandler handler = new DefaultHandler()
        {
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
            {
                //detect start element
                                //read the attribute of the element 
             }

             public void endElement(String uri, String localName, String qName) throws SAXException 
             {
                             //detect the end of the element
                         }

             public void characters(char ch[], int start, int length) throws SAXException 
             {
                             //read the element data
             }
        };

        try
        {    
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser saxParser = saxParserFactory.newSAXParser();
            InputStream inputStream = new ByteArrayInputStream(sXMLResult.getBytes("UTF-8"));
            Reader reader = new InputStreamReader(inputStream,"UTF-8");

            InputSource isReader = new InputSource(reader);
            isReader.setEncoding("UTF-8");

            saxParser.parse(isReader, handler); 
        }
        catch (UnsupportedEncodingException e){}
        catch (ParserConfigurationException e){} 
        catch (SAXException e) {}
        catch (IOException e) {}        
    }

Hope this will help you.

Upvotes: 1

Related Questions