DOM 方式解析 XML

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("tree.xml");
            //根据标签名获取节点集合
            NodeList nodeList  = doc.getElementsByTagName("item");
            for (int i = 0; i < nodeList.getLength(); i++) {
                //获取单个节点
                Node node = nodeList.item(i);
                //获取节点属性集合
                NamedNodeMap attrs = node.getAttributes();
                //遍历属性
                for (int j = 0; j < attrs.getLength(); j++) {
                    Node attr = attrs.item(j);
                    System.out.println("属性名:"+attr.getNodeName());
                    System.out.println("属性值:"+attr.getNodeValue());
                }
//                //节点转化为Element对象获取属性值
//                Element ele = (Element)node;
//                System.out.println("属性值:"+ele.getAttribute("id"));
                //获取子节点集合
                NodeList childList = node.getChildNodes();
                for (int k = 0; k < childList.getLength(); k++) {
                    Node child = childList.item(k);
                    //判断子节点类型为Element类型非Text文本类型
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("节点间文本:"+child.getTextContent());
                        //
                        System.out.println("节点间文本:"+child.getFirstChild().getNodeValue());
                        //注:child.getNodeValue()不能获取节点间文本,因节点间文本为节点的子级,是其子节点的NodeValue
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

posted @ 2015-01-19 10:08  知之为知之  阅读(107)  评论(0编辑  收藏  举报