package com.lan.xml; 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 Demo2 { public static void main(String[] args) { //1.创建工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //2.得到dom解析器 DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } //3.解析xml文档,得到代表文档的document try { Document document = builder.parse("src/book.xml"); NodeList nlist = document.getElementsByTagName("书名"); Node bookname = nlist.item(0); String content = bookname.getTextContent(); System.out.println(content); System.out.println(); //强行转换Element(前提是知道获取的Node为Element Element bookNameChange = (Element) nlist.item(0); String value = bookNameChange.getAttribute("name"); System.out.println(value); System.out.println(); //递归遍历打印标签 //得到根结点 Node root = document.getElementsByTagName("书架").item(0); list(root); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //递归遍历打印标签 private static void list(Node root) { if (root instanceof Element) { System.out.println(root.getNodeName()); } //System.out.println(root.getNodeName()); NodeList list = root.getChildNodes(); for(int i=0;i<list.getLength();i++){ Node Child = list.item(i); list(Child); } } }
<?xml version="1.0" encoding="UTF-8" ?> <书架> <书> <书名 name="xxxxx">lan</书名> <作者>lan</作者> <售价>100000000000000000元</售价> </书> </书架>