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

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/mrcharles/p/4731756.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值