DOM解析XML文件
程序员文章站
2022-04-30 10:00:41
...
目录结构
xml文件数据
<?xml version='1.0' encoding='UTF-8'?>
<books>
<book id='1'>
<name>Bug速成宝典</name>
<price>67</price>
<language>Chinese</language>
</book>
<book id='2'>
<name>Mysql从删库到跑路</name>
<price>100</price>
<year>2018</year>
<language>English</language>
</book>
</books>
DOM解析XML代码
package main.java;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* 使用DOM解析xml
*/
public class DOMTest {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document parse = db.parse("books.xml");
//获得所有的book节点
NodeList books = parse.getElementsByTagName("book");
//遍历获得每一个book节点
for (int i = 0; i < books.getLength(); i++) {
System.out.println("----开始解析第" + (i + 1) + "本书----");
//因为book标签只有一个属性,所以直接获取,向下强转为Element
//前提是只有一个属性
/*Element book = (Element) books.item(i);
String id = book.getAttribute("id");
System.out.println("属性名为id-------属性值为" + id);*/
Node nodeList = books.item(i);
//获得book节点的所有属性
NamedNodeMap attributes = nodeList.getAttributes();
//获得book的子节点数
System.out.println("第"+(i + 1)+ "本书的节点数为:"+nodeList.getChildNodes().getLength());
for (int j = 0; j < attributes.getLength(); j++) {
Node item = attributes.item(j);
//获得属性名和属性值
String name = item.getNodeName();
String value = item.getNodeValue();
System.out.print("属性名为:" + name);
System.out.println("----属性值为:" + value);
}
//获得book节点的所有子节点
NodeList childNodes = nodeList.getChildNodes();
//遍历获得每一个子节点
for (int k = 0; k < childNodes.getLength(); k++) {
Node chileItem = childNodes.item(k);
//判断节点类型是否是Element类型,这种因为这种解析会把book节点下的空格都算成是子节点
if (chileItem.getNodeType() == Node.ELEMENT_NODE) {
String nodeName = chileItem.getNodeName();
String nodeValue = chileItem.getNodeValue();
System.out.print("属性名为:" + nodeName);
System.out.println("----属性值为:" + chileItem.getTextContent());
}
}
}
}
}
结果展示