java源文件分享地址:java
連接:https://pan.baidu.com/s/13RpYh-d0Zw11fahkUJP0Ug
提取碼:3fpe
複製這段內容後打開百度網盤手機App,操做更方便哦node
xml文件信息:dom
<?xml version="1.0" encoding="GB2312"?> <PhoneInfo> <Brand name="華爲"> <Type name="U8650"/> <Type name="HW123"/> <Type name="HW321"/> </Brand> <Brand name="蘋果"> <Type name="iPhone4"/> </Brand> </PhoneInfo>
DOM模式讀取xml文件信息:ui
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 DOMDemo { private Document document = null; public void getDocument(){ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder=factory.newDocumentBuilder(); document=builder.parse("收藏信息.xml"); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void show() { //找到全部的Brand NodeList nodeList = document.getElementsByTagName("Brand"); //遍歷每個Brand for(int i = 0;i<nodeList.getLength();i++) { Node node = nodeList.item(i); //轉成元素類型 Element eleBrand = (Element)node; System.out.println("品牌:"+eleBrand.getAttribute("name")); //找到當前Brand的全部子節點 NodeList typeList = eleBrand.getChildNodes(); //遍歷每個子節點 for(int j = 0;j<typeList.getLength();j++) { Node typeNode = typeList.item(j); //由於Brand的子節點中可能有非元素節點,好比屬性節點、文本節點 //因此要先判斷該子節點是不是一個元素節點,若是是才能進行強轉 //typeNode.getNodeType()這個方法是獲取到當前節點的節點類型——元素節點、屬性節點、文本節點 if(typeNode.getNodeType()==Node.ELEMENT_NODE) { //轉換成元素對象 Element eleType = (Element)typeNode; System.out.println("\t型號:"+eleType.getAttribute("name")); } } } } public static void main(String[] args) { DOMDemo dd = new DOMDemo(); dd.getDocument(); dd.show(); } }
輸出結果爲:spa
品牌:華爲
型號:U8650
型號:HW123
型號:HW321
品牌:蘋果
型號:iPhone4