import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Text {

public static void main(String[] args) {
try{
//得到DOM解析器的工厂实例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//从DOM工厂获得DOM解析器
DocumentBuilder db = dbf.newDocumentBuilder();
//解析XML文档得到一个Document,即DOM树;
Document doc = db.parse("src/收藏信息.xml");
//得到<Brand>节点列表信息
NodeList brandList = doc.getElementsByTagName("Brand");
//循环Brand信息
for(int i=0; i<brandList.getLength(); i++) {
//获取第i个brand信息
Node brand = brandList.item(i);
//获取第i个brand元素的属性值并输出
Element element = (Element) brand;
String attValue = element.getAttribute("name");
// System.out.print(attValue);
//获取第i个brand元素的所有子元素的name属性
NodeList haha = brand.getChildNodes();
for(int j=0; j<haha.getLength(); j++) {
//type节点
Node zheg = haha.item(j);

Element typeElement = (Element)zheg;//这里怎么错啦
//获取手机型号
String str = typeElement.getAttribute("name");
// System.out.println(type);
System.out.println("手机信息" + attValue + str);
}
}
}catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

解决方案 »

  1.   

    Node有很多子类的,比如Text,你应该先判断下是否是Element再转换就可以了
      

  2.   

    //获取第i个brand元素的所有子元素的name属性
    NodeList haha = brand.getChildNodes();
    for(int j=0; j<haha.getLength(); j++) {
    //type节点
    Node zheg = haha.item(j);Element typeElement = (Element)zheg;//这里怎么错啦节点分文本和元素两种,你需要分类考虑
    NodeList haha = brand.getChildNodes();
    for(int j=0; j<haha.getLength(); j++) {
    //type节点
    Node zheg = haha.item(j);
    if(zheg.getNodeType()==Node.ELEMENT_NODE){  //add
    Element typeElement = (Element)zheg;
    ......