1 /** 2 * 获取XML文件的信息 3 */ 4 import java.io.IOException; 5 import javax.xml.parsers.DocumentBuilder; 6 import javax.xml.parsers.DocumentBuilderFactory; 7 import javax.xml.parsers.ParserConfigurationException; 8 import org.w3c.dom.Document; 9 import org.w3c.dom.Element; 10 import org.w3c.dom.Node; 11 import org.w3c.dom.NodeList; 12 import org.xml.sax.SAXException; 13 14 public class DOMDemo { 15 private Document document = null; 16 public void getDocument(){ 17 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); 18 try { 19 DocumentBuilder builder=factory.newDocumentBuilder(); 20 document=builder.parse("手机信息.xml"); 21 } catch (ParserConfigurationException e) { 22 e.printStackTrace(); 23 } catch (SAXException e) { 24 e.printStackTrace(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 public void show() { 30 //找到所有的Brand 31 NodeList nodelist = document.getElementsByTagName("Brand"); 32 //遍历每一个Brand 33 for(int i = 0;i<nodelist.getLength();i++) { 34 Node node = nodelist.item(i); 35 //转为元素类型 36 Element eleBrand = (Element)node; 37 System.out.println("品牌:"+eleBrand.getAttribute("name")); 38 39 //找到每一个Type 40 NodeList typelist = eleBrand.getElementsByTagName("Type"); 41 //遍历 42 for(int j = 0;j<typelist.getLength();j++) { 43 Node node2 = typelist.item(j); 44 //因为Brand的子节点中可能有非元素节点,比如属性节点、文本节点 45 //所以要先判断该子节点是否是一个元素节点,如果是才能进行强转 46 //node2.getNodeType()这个方法是获取到当前节点的节点类型——元素节点、属性节点、文本节点 47 if(node2.getNodeType()==Node.ELEMENT_NODE) { 48 Element eleType = (Element)node2; 49 System.out.println(" 型号:"+eleType.getAttribute("name")); 50 } 51 } 52 } 53 54 } 55 56 public static void main(String[] args) { 57 DOMDemo dd = new DOMDemo(); 58 dd.getDocument(); 59 dd.show(); 60 } 61 62 }
输出: