zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    Orchard Oracle 支持
    讽刺的是,我在linux下使用最多的命令,竟然是windows的
    学习bash
    提高分布式环境中程序启动性能的一个方法
    MQTT X v1.4.1 正式发布
    社区力量|因为 EMQ,他上了微博热搜
    不止是现在,更关注未来:EMQ 携手高校加强物联网人才培养
    EMQ 助力西安增材制造国家研究院打造增材智能车间平台
    Kuiper 1.0.1 正式发布
    MQTT X v1.4.0 正式发布
  • 原文地址:https://www.cnblogs.com/mrcharles/p/4731756.html
Copyright © 2011-2022 走看看