一、Java中操作DOM中常用的类
- Node
数据类型基类
- Element
最常用的类
- Attr
Element的属性
- Text
Element or Attr的内容
- Document
代表整个XML文档,代表DOM tree
二、xml文件
1<?xml version = "1.0" encoding = "utf-8"?>
2<books>
3 <book id="1">
4 <name>冰与火之歌</name>
5 <author>张三</author>
6 <pice>99</pice>
7 </book>
8 <book id="2">
9 <name>葫芦娃</name>
10 <pice>99</pice>
11 <year>1993</year>
12 </book>
13</books>
三、Dom解析XML案例Demo
1package com.da.dom;
2
3import javax.xml.parsers.DocumentBuilder;
4import javax.xml.parsers.DocumentBuilderFactory;
5
6import org.w3c.dom.Document;
7import org.w3c.dom.Element;
8import org.w3c.dom.Node;
9import org.w3c.dom.NodeList;
10
11public class DomTest {
12
13 public static void main(String[] args) {
14 //创建一个DocumentBuilderFactory对象
15 DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
16 try {
17 //创建DocumentBuilder对象
18 DocumentBuilder db = documentBuilder.newDocumentBuilder();
19 //通过DocumentBuilder中的parse方法加载book。xml文件到当前项目下
20 Document document = db.parse("books.xml");
21 //获取所有book节点的集合
22 NodeList nodeList = document.getElementsByTagName("book");
23 //遍历每个book节点
24 for (int i = 0; i < nodeList.getLength(); i++) {
25 System.out.println("==========第"+(i+1)+"本==========");
26// Node book = nodeList.item(i);
27// NamedNodeMap attributes = book.getAttributes();
28// //不知道当前节点下有多少参数属性值
29// for (int j = 0; j < attributes.getLength(); j++) {
30// Node item = attributes.item(j);
31// System.out.print("获取属性名:"+item.getNodeName());
32// System.out.println("获取属性值:"+item.getNodeValue());
33// }
34 //确切当前参数下有多少参数属性值
35 Element element = (Element) nodeList.item(i);
36 System.out.println("id值:"+element.getAttribute("id"));
37 //获取book下面的子节点
38 NodeList childNodes = nodeList.item(i).getChildNodes();
39 for (int j = 0; j < childNodes.getLength(); j++) {
40 if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
41 System.out.print(childNodes.item(j).getNodeName()+":");
42 System.out.println(childNodes.item(j).getTextContent());
43 };
44 }
45
46 }
47 } catch (Exception e) {
48 e.printStackTrace();
49 }
50 }
51}