XML解析,出现ClassCastException 原因
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class sddddddddddddd {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// TODO Auto-generated method stub
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//从DOM工厂获得解析器
DocumentBuilder db = dbf.newDocumentBuilder();
//获得DOM树,解析出来文档
Document doc=db.parse("D:\\Phone.xml");
//获得节点信息
System.out.println("hh");
NodeList brandlist = doc.getElementsByTagName("Brand");
for (int i=0;i<brandlist.getLength();i++){
System.out.println("hh");
Node brand = brandlist.item(i);
Element element = (Element) brand;
String attrValue = element.getAttribute("name");
NodeList types = element.getChildNodes();
System.out.println("hh");
for (int j=0;j<types.getLength();j++){
Element typelement = (Element) types.item(j);
String type = typelement.getAttribute("name");
System.out.println(attrValue+type);
System.out.println("hh");
}
}
}
}
原因在于,XML中间不能有空格,在网络上也有很多人指出了这个问题。
<?xml version="1.0" encoding="utf-8" ?>
<phone><Brand name="华为"><Type name="mate7"/><Type name="P7"/><Type name="荣耀7"/></Brand><Brand name="苹果"><Type name="Iphone5"/><Type name="Iphone6"/><Type name="Iphone7"/></Brand></phone>
如果有空格或者回车存在,就会导致错误的解析,API认为也是一个节点,结果解析出来什么都没有,就是null
posted on 2015-05-04 20:00 MrCharles在cnblogs 阅读(107) 评论(0) 编辑 收藏 举报