加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

获取XML的文件信息

发布时间:2020-12-16 23:36:21 所属栏目:百科 来源:网络整理
导读:? 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.D

?

 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("t型号:"+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 }

输出:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读