Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to。org.w3c.dom.Element 代码: NodeList nl = doc.getElementsByTagName("Brand"); for (int i = 0; i < nl.getLength(); i++) { Element brandNode = (Element) nl.item(i); NodeList childList = brandNode.getChildNodes(); for (int j = 0; j < childList.getLength(); j++) { Element typeElement = (Element) childList.item(j); //Exception String typeName = typeElement.getAttribute("name"); System.out.println("手机:"+brandName+typeName); } } xml code: <?xml version="1.0" encoding="utf-8"?> <PhoneInfo> <Brand name="苹果"> <Type name="IPhone4"/> <Type name="IPhone5"/> </Brand> <Brand name="联想"> <Type name="A60"/> </Brand> </PhoneInfo> 请问这是什么原因造成的?
提问者采纳
2012-03-28 07:05
从你的代码上看不出什么来。 Element typeElement = (Element) childList.item(j); //Exception 错误的原因是 com.sun.org.apache.xerces.internal.dom.DeferredTextImpl 不能转成 org.w3c.dom.Element 你看一下你引用的类吗,估计是同名的你引错了。导致强转类型时出错。
-
追问
-
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; 我引用的类就这几个,你看有问题吗?
-
回答
-
这么看是没有问题。 提示中的这个 com.sun.org.apache.xerces.internal.dom.DeferredTextImpl 是什么造成的? 从这里找一下原因吧
-
追问
-
在百度里面实在是搜不到答案,然后就Google了一下,那些英文让我花了大把的时间才才搞清楚。 问题主要是在我的xml文档中元素之间使用了空格符,在getChildNodes()的时候系统把空格当成了文本节点,所以在遍历ChildNodes的时候将文本节点强制转换成Element类型就会出错。 谢谢你帮忙哈!
-
提问者评价
-
3q