01 | package demo; |
02 |
03 |
04 | import java.io.File; |
05 | import java.io.InputStream; |
06 | import java.util.Properties; |
07 |
08 |
09 | import javax.xml.parsers.DocumentBuilder; |
10 | import javax.xml.parsers.DocumentBuilderFactory; |
11 | import javax.xml.parsers.ParserConfigurationException; |
12 |
13 | import org.w3c.dom.Document; |
14 | import org.w3c.dom.Element; |
15 | import org.w3c.dom.Node; |
16 | import org.w3c.dom.NodeList; |
17 | //DOM解析 |
18 | public class MyXMLDOM { |
19 | public static void main(String[] args) { |
20 | long lasting=System.currentTimeMillis(); |
21 | try { |
22 | File f= new File( "src/a.xml" ); |
23 | // if(f.exists()){ |
24 | // System.out.println("存在"); |
25 | // }else{ |
26 | // System.out.println("不存在"); |
27 | // return; |
28 | // } |
29 | //获得一个DOM工厂 |
30 | DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); |
31 | //获得一个dom解析器 |
32 | DocumentBuilder builder=factory.newDocumentBuilder(); |
33 | //读配置文件 |
34 | Document doc=builder.parse(f); |
35 | //开始打印 |
36 | //getDocumentElement 获取根节点 |
37 | System.out.println( "<" +doc.getDocumentElement().getNodeName()+ ">" ); |
38 | //判断该根节点下是否有子节点 |
39 | if (doc.getDocumentElement().hasChildNodes()){ |
40 | //利用for循环,把第一个儿子开始,一次判断下个同兄弟节点是否存在 |
41 | for (Node n=doc.getDocumentElement().getFirstChild();n!= null ;n=n.getNextSibling()){ |
42 | //节点有很多,ELEMENT_NODE是元素节点,数字值是1 |
43 | if (n.getNodeType()==Node.ELEMENT_NODE){ |
44 | System.out.println( " <" +n.getNodeName()+ ">" ); |
45 | if (n.hasChildNodes()){ |
46 | for (Node n1=n.getFirstChild();n1!= null ;n1=n1.getNextSibling()){ |
47 | if (n1.getNodeType()==Node.ELEMENT_NODE){ |
48 | System.out.print( " <" +n1.getNodeName()+ ">" ); |
49 | //<name>xb</name> 注:xb算name的下一个节点 即文本节点Text_NODE |
50 | System.out.print(n1.getFirstChild().getNodeValue()); |
51 | |
52 | System.out.println( " </" +n1.getNodeName()+ ">" ); |
53 | } |
54 | } |
55 | } |
56 | System.out.println( " </" +n.getNodeName()+ ">" ); |
57 | } |
58 | } |
59 | } |
60 | System.out.println( "</" +doc.getDocumentElement().getNodeName()+ ">" ); |
61 | System.out.println( "运行时间" +(System.currentTimeMillis()-lasting)+ "毫秒" ); |
62 | } catch (Exception e) { |
63 | e.printStackTrace(); |
64 | } |
65 |
66 | } |
67 | } |