Android XML:无法将节点强制转换为元素

时间:2012-01-15 14:56:26

标签: android xml

我正在尝试读取xml文件,但它一直告诉我:java.lang.ClassCastException:org.apache.harmony.xml.dom.ElementImpl无法强制转换为android.renderscript.Element

为什么我不能将nNode转换为元素?

    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文件:

<?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>

2 个答案:

答案 0 :(得分:9)

你导入错误的东西:

替换:import android.renderscript.Element;

import org.w3c.dom.Element;

然后继续:

如果你使用DOMParser,这里有一些帮助方法:

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;
}

然后在你的例子中:

        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!
        }

答案 1 :(得分:1)

尝试像这样使用XML Parser

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) {}        
    }

希望这会对你有所帮助。