• 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

  • 相关阅读:
    链接被点击时不出现虚线框的方法
    label 和 legend标签的用法
    了解常见的浏览器内核 Trident,Geckos,Presto,Webkit
    DOCTYPE声明的几种类型
    Angularjs基础教程
    理解angular中的module和injector,即依赖注入
    es5 api
    css3_note
    canvas 基础知识
    uglifyjs note
  • 原文地址:https://www.cnblogs.com/mrcharles/p/11879942.html
Copyright © 2020-2023  润新知