package cn.itcast.dom; import java.io.FileInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class DomTest { public static void main(String[] args) throws Exception { //1. 得到代表xml 文档的 Document 对象: 利用 DocumentBuilderFactory 得到 DocumentBuilder, 再得到 Document 对象 Document document = null; DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); document = db.parse(new FileInputStream("customer.xml")); //2. 获取 xml 文档的根节点 Element rootElement = document.getDocumentElement(); //System.out.println(rootElement.getNodeName()); //3. 得到根节点所有 customer 子节点 NodeList nodeList = rootElement.getElementsByTagName("customer"); //System.out.println(nodeList.getLength()); //4. 遍历得到的 customer 节点的集合 for(int i = 0; i < nodeList.getLength(); i++){ Element ele = (Element) nodeList.item(i); //System.out.println(ele.getNodeName()); //5. 得到 customer 节点的 id 属性值 String id = ele.getAttribute("id"); //6. 得到当前 customer 节点的 name, age, address 子节点的文本值 //** 在 <name>Mike</name> 中, Mike 是 name 节点的文本子节点!! Element nameElement = (Element) ele.getElementsByTagName("name").item(0); String name = nameElement.getFirstChild().getNodeValue(); String age = ele.getElementsByTagName("age").item(0).getFirstChild().getNodeValue(); String address = ele.getElementsByTagName("address").item(0).getFirstChild().getNodeValue(); System.out.println("id: " + id + ", name: " + name + ", age: " + age + ", address: " + address); } } }