用 DOM 读取一个 XML 文档(二)


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<学生名册>
<学生 学号="1">
<姓名>张三</姓名>
<!-- haha -->
<性别>男</性别>
<年龄>20</年龄>
</学生>
<学生 学号="2">
<姓名>李四</姓名>
<性别>女</性别>
<年龄>19</年龄>
</学生>
<学生 学号="3">
<姓名>王五</姓名>
<性别>男</性别>
<年龄>21</年龄>
</学生>
</学生名册>




package com.syh.xml.dom;

import java.io.File;

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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomTest3 {

public static void main(String[] args) throws Exception {


DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance() ;

DocumentBuilder db = dbf.newDocumentBuilder() ;

Document doc = db.parse(new File("student.xml")) ;

// System.out.println(doc.getXmlEncoding());
// System.out.println(doc.getXmlVersion());
// System.out.println(doc.getXmlStandalone());

//获得 XML 文档的根元素节点
Element rootEle = doc.getDocumentElement() ;
System.out.println(rootEle.getTagName());

//这里一定要注意一下空格!因为空格也是属于节点的孩子的组成部分。
NodeList list = rootEle.getChildNodes() ;
System.out.println(list.getLength());

for(int i = 0 ; i < list.getLength() ; i ++ ) {
System.out.println(list.item(i).getNodeName());
}

System.out.println("----------------节点的类型和节点值-----------------");

for(int i = 0 ; i < list.getLength() ; i ++) {

Node n = list.item(i) ;

//打印节点的类型和节点值
System.out.println(n.getNodeType() + " : " + n.getNodeValue());

}

System.out.println("----------------打印所有节点的文本(不包括节点的属性!但是包括空白!因为空白也是属于文本的)-----------------");

for(int i = 0 ; i < list.getLength() ; i ++ ) {
Node n = list.item(i) ;

System.out.println(n.getTextContent());
}

System.out.println("-----------------拿到属性----------------");

NodeList nodeList = doc.getElementsByTagName("学生") ;

for(int i = 0 ; i < nodeList.getLength() ; i ++) {

NamedNodeMap nnm = nodeList.item(i).getAttributes() ;

String attrName = nnm.item(0).getNodeName() ;
System.out.print(attrName);

System.out.print(" = ");

String attrValue = nnm.item(0).getNodeValue() ;
System.out.print(attrValue);

System.out.println();

}

}
}



控制台上出现的效果:


学生名册
7
#text
学生
#text
学生
#text
学生
#text
----------------节点的类型和节点值-----------------
3 :

1 : null
3 :

1 : null
3 :

1 : null
3 :

----------------打印所有节点的文本(不包括节点的属性!但是包括空白!因为空白也是属于文本的)-----------------



张三


20




李四

19




王五

21



-----------------拿到属性----------------
学号 = 1
学号 = 2
学号 = 3


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值