DOM解析式注意文本节点

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        try {
            db = dbf.newDocumentBuilder();
            Document doc = db.parse("src/cn/xiong/xml/exercise04/收藏信息.xml");
            NodeList brandList = doc.getElementsByTagName("Brand");
            for(int i=0; i<brandList.getLength();i++){
                Node brand = brandList.item(i);
                Element be = (Element) brand;
                String brandInfo = be.getAttribute("name");
                System.out.println("品牌:"+brandInfo);
                NodeList types = be.getChildNodes();
                for(int j=0;j<types.getLength();j++){
                    Node type = types.item(j);
                    if(type.getNodeType()==Node.ELEMENT_NODE){
                        Element te= (Element) type;
                        String typeInfo = te.getAttribute("name");
                        System.out.println("\t型号:"+typeInfo);
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
节点判断时注意type.getNodeType()==Node.ELEMENT_NODE,剔除因空格或换行造成的文本节点

posted @ 2016-05-20 15:12  yanweijin  阅读(164)  评论(0)    收藏  举报