DOM解析XML

一,创建DOM解析器工厂对象         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

二,创建解析器对象              DocumentBuilder builder = factory.newDocumentBuilder();

三,指定解析谁(xml文件或数据)      Document doc = builder.parse(conn.getInputStream());      得到的是文档对象

四,解析 想要解析的元素节点         NodeList   n = doc.getElementsByTagName("要解析的元素");    得到的是节点数组

五,遍历                   for (int i = 0; i < nl.getLength(); i++) { 

                         Node book = n.item(i);                  得到的是book节点
                //获取book节点的所有属性集合
                NamedNodeMap attrs = book.getAttributes();
                System.out.println("第"+(i+1)+"本书共有"+attrs.getLength()+"个属性");
                //遍历book的属性
                for(int j = 0;j<attrs.getLength();j++){
                    //通过item方法获取book节点的属性
                    Node attr = attrs.item(j);
                    //获取属性名
                    System.out.print("属性名:"+attr.getNodeName());
                    //获取属性值
                    System.out.println("--属性值"+attr.getNodeValue());
                    NodeList chilNod = book.getChildNodes();
                    System.out.println("第"+(i+1)+"本书共有"+chilNod.getLength()+"个子节点");
                    for(int k = 0;k<chilNod.getLength();k++){
                        Node chil = chilNod.item(k);                  
                        //区分text 类型node
                        if(chilNod.item(k).getNodeType() == Node.ELEMENT_NODE){
                            System.out.print("子节点名:"+chil.getNodeName()+":");
                            System.out.println("    子节点值:"+chilNod.item(k).getFirstChild().getNodeValue());
                          //System.out.println("子节点值:"+chilNod.item(k).getTextContent());
                        }                                     
                    }

                      }

原文地址:https://www.cnblogs.com/liuqu/p/8570109.html