XML的读取

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>体测数据</name>
<author>1佳</author>
<year>1631</year>
<price>37.5</price>
</book>
<book id="2">
<name>体测分析</name>
<author>2佳</author>
<year>1632</year>
<price>38.5</price>
</book>
<book id="3">
<name>体测动态</name>
<author>3佳</author>
<year>1633</year>
<price>39.5</price>
</book>
</bookstore>
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
*
*
* @author Administrator
*/
public class readdom{
public static void main(String[] args) {
// 创建一个DocumentBuilderFactory对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// 创建DocumentBuilder对象,使用parse方法加载xml文件到当前项目下
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse("src/xml.xml");
// 获取所有book节点的集合,是所有一级子节点的list集合
NodeList bookList = document.getElementsByTagName("book");
System.out.println("一共有:" + bookList.getLength() + "本书");
// 遍历每一个book节点,获取的是整个书对象
for (int i = 0; i < bookList.getLength(); i++) {
System.out.println("======开始遍历第" + (i + 1) + "本书=======");
// 通过item(i)方法获取具体book节点,索引从0开始
Node book = bookList.item(i);
// 获取book节点的所有属性集合,是一个map集合
NamedNodeMap attrs = book.getAttributes();
System.out.println("第" + (i + 1) + "本书共有" + attrs.getLength() + "个属性:");
// 遍历book的具体属性
for (int j = 0; j < attrs.getLength(); j++) {
// 通过item方法获取book节点的某个属性
Node item = attrs.item(j);
// 获取节点属性名
String nodeName = item.getNodeName();
// 获取节点属性值
String nodeValue = item.getNodeValue();
System.out .println("节点名:" + nodeName + ";节点值:" + nodeValue);
}
// 遍历book下面的次节点
NodeList childNodes = book.getChildNodes();
System.out.println("第" + (i + 1) + "本书共有" + childNodes.getLength() + "个子节点:");
for (int k = 0; k < childNodes.getLength(); k++) {
// 区分出text类型的node以及element类型的node,只有是element类型的node才输出
if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
// 获取节点的名称
System.out.print(childNodes.item(k).getNodeName() + "------");
/**
* 获取第一个节点的节点值 <name>放学后</name>
* name之间的部分会当成一个节点,所以"放学后"会当成第一个子节点的节点值
*/
System.out.println(childNodes.item(k).getFirstChild() .getNodeValue());

/**
* getTextContent()会获取<name></name>的所有子节点的节点值
* <name><a>aa</a>bb</name>:结果为:aabb
* 而.getFirstChild().getNodeValue()的结果为null
* 因为第一个节点a为element节点,其节点值为null
*/
// System.out.println(childNodes.item(k).getTextContent());
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值