Dom方式解析XML

public class TestXML {

    public static void main(String[] args) throws SAXException, IOException {
       //Dom方式解析XML
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document =  db.parse("books.xml");
        NodeList bookList = document.getElementsByTagName("book");
        System.out.println("一共有"+bookList.getLength()+"本书");
        for (int i = 0; i < bookList.getLength(); i++) {
            Node node =  bookList.item(i);
            NamedNodeMap attrs = node.getAttributes();
            System.out.println("第"+(i+1)+"本书共有"+attrs.getLength()+"个属性");
            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr = attrs.item(j);
                System.out.print("属性名:"+attr.getNodeName());
                System.out.println("--属性值:"+attr.getNodeValue());
            }
            NodeList child = node.getChildNodes();
            for (int j = 0; j < child.getLength(); j++) {
                if(child.item(j).getNodeType()==Node.ELEMENT_NODE)
                     System.out.println(child.item(j).getNodeName()+":"+child.item(j).getTextContent());
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    }

}
posted @ 2016-10-09 20:21  虫儿ls  Views(133)  Comments(0Edit  收藏  举报