【自动化__持续集成】___java___XMl___DOM读

一、代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.wujianbo.five;
 
import javax.sound.midi.Sequence;
import javax.xml.bind.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class Demo08 {
 
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        Demo08 demo08= new Demo08();
        demo08.readXmlByDom();
 
    }
     
    private void readXmlByDom() throws Exception {
        // TODO Auto-generated method stub
        DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
        DocumentBuilder builder= factory.newDocumentBuilder();
         
        String xmlName= System.getProperty("user.dir") + "\\data\\Students.xml";
        //System.out.println(xmlName);
        Document doc= builder.parse(xmlName);
        doc.normalize();
        NodeList students= doc.getElementsByTagName("student");
        //Element s1= (Element)students.item(0);
        org.w3c.dom.Element s1= (org.w3c.dom.Element)students.item(0);
        System.out.println(s1.getAttribute("sequence"));
         
        Node id1= s1.getElementsByTagName("id").item(0);
        System.out.println(id1.getFirstChild().getNodeValue());
        System.out.println("===========================================");
        for(int i=0;i<students.getLength(); i++) {
            org.w3c.dom.Element son= (org.w3c.dom.Element)students.item(i);
            for(Node node= son.getFirstChild(); node!=null; node= node.getNextSibling()) {
                if(node.getNodeType() == node.ELEMENT_NODE) {
                    String name= node.getNodeName();
                    String value= node.getFirstChild().getNodeValue();
                    System.out.print(name + ": " +value);
                }
            }
            System.out.println();
        }
        System.out.println("==========================================");
    }
 
}

 



如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
posted @   18513757531  阅读(122)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示