xml文件
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book id="1"> <name>你好</name> <author>李四</author> <price>80</price> </book> <book id="2"> <name>你好2</name> <author>李四2</author> <price>81</price> </book> </bookstore>
java檔案
package cn.lonecloud.xml; 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; public class DomXML { public static void main(String[] args) throws Exception { //先建立一個DocumentBuilderFactory物件 DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); //建立一個buildfactory物件 DocumentBuilder db=dbf.newDocumentBuilder(); //獲取xml檔案 Document document=db.parse("demo.xml"); //獲取root樹的Element Element e1=document.getDocumentElement(); //獲取子元素的子節點 if (e1!=null) { NodeList list=e1.getChildNodes(); if (list!=null) { //遍歷書子節點 for (int i = 0; i < list.getLength(); i++) { Node node=list.item(i); if (node!=null) { NodeList child=node.getChildNodes(); for (int j = 0; j < child.getLength(); j++) { Node n=child.item(j); //獲取屬性名稱文字 if (n.getNodeType()==Node.ELEMENT_NODE) { //獲取節點名稱 System.out.println(n.getNodeName()); //獲取這個節點值 System.out.println(n.getFirstChild().getNodeValue()); //獲取節點的的值下的所有文字 System.out.println(n.getTextContent()); } } } } } } } }