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