JavaDom 学习笔记

本文对 Java Dom 解析 XML 文件进行了一次梳理,包含所使用测试的 XML 文件 .JAVA 文件


1.Test.java


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DomUtils utils = new DomUtils();
		try {
			ArrayList<Book> books = utils.readFromXML(new FileInputStream(
					"D:\\book.xml"));
			System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
			for (int i = 0; i < books.size(); i++) {
				System.out.println("id:" + books.get(i).getId() + "name:"
						+ books.get(i).getBookName() + "price:"
						+ books.get(i).getBookPrice()+books.get(i).getTest());
			}
			System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}

2.DomUtils.java


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

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

public class DomUtils {

	public ArrayList<Book> readFromXML(InputStream inputStream) {
		ArrayList<Book> list = new ArrayList<Book>();
		// 创建 DocumentBuilderFactory 对象
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;

		try {
			// 从 DoccumentBuilderFactory 对象中获取一个 DocumentBuilder 对象
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			System.out.println("读取失败,不能正常获取 DocumentBuilder");
			System.exit(1);// 0 表示正常退出 1表示异常退出
		}
		Document document = null;

		// 使用 DocumentBulider 对象将 XML 文件输入流转化为一个 Document 对象
		try {
			document = builder.parse(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("读取失败,不能正常获取 Document ");
			System.exit(1);// 0 表示正常退出 1表示异常退出
		}
		Element rootElement = document.getDocumentElement();
		System.out.println("根节点");
		System.out.println(rootElement);
		// 获取根节点下的 book 节点链表
		System.out.println("获取根节点的 book 节点");
		NodeList bookNodes = rootElement.getElementsByTagName("book");
		NodeList bookNodes1 = rootElement.getElementsByTagName("Test");
		System.out.println(bookNodes.item(0));
		System.out.println(bookNodes.item(1));
		System.out.println(bookNodes1.item(0));
		System.out.println("DomUtils======================");
		for (int i = 0; i < bookNodes.getLength(); i++) {// 遍历 book 节点链表
			Book book = new Book();
			Element bookElement = (Element) bookNodes.item(i);
			String id = bookElement.getAttribute("id");
			book.setId(id);
			// 获取 book 节点下的子节点链表
			NodeList childNodeList = bookElement.getChildNodes();
			// 测试
			System.out.println("获取 book 节点下的子节点");
			System.out.println(childNodeList.item(0));
//			System.out.println("childNodeList.item(0).getNodeType() is:"+childNodeList.item(0).getNodeType());
			System.out.println(childNodeList.item(1));
			System.out.println(childNodeList.item(2));
			System.out.println(childNodeList.item(3));
			System.out.println(childNodeList.item(4));
			System.out.println(childNodeList.item(5));
			System.out.println(childNodeList.item(6));
			for (int j = 0; j < childNodeList.getLength(); j++) {
				// 判断是否为节点类型,是正常节点类型才能获取节点信息
				if (childNodeList.item(j).getNodeType() == Node.ELEMENT_NODE) {
					if ("name".equals(childNodeList.item(j).getNodeName())) {
						book.setBookName(childNodeList.item(j).getFirstChild()
								.getNodeValue());
					} else if ("price".equals(childNodeList.item(j)
							.getNodeName())) {
						book.setBookPrice(Float.parseFloat(childNodeList
								.item(j).getFirstChild().getNodeValue()));
					} else if ("test".equals(childNodeList.item(j)
							.getNodeName())) {
						book.setTest(childNodeList.item(j).getFirstChild()
								.getNodeValue());
						//测试
						System.out.println("childNodeList.item(j) is:"
								+ childNodeList.item(j));
						System.out
								.println("childNodeList.item(j).getFirstChild() is:"
										+ childNodeList.item(j).getFirstChild());
						System.out
								.println("childNodeList.item(j).getFirstChild().getNodeValue() is:"
										+ childNodeList.item(j).getFirstChild()
												.getNodeValue());
						//测试
						System.out.println("childNodeList.item(j).getNodeType() is:"+childNodeList.item(j).getNodeType());
					}
				}
			}
			list.add(book);
		}

		return list;

	}
}

3.Book.java


public class Book {
	private String id;
	private String bookName;
	private float bookPrice;
	private String test;

	public String getId() {
		return id;
	}

	public String getTest() {
		return test;
	}

	public void setTest(String test) {
		this.test = test;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public float getBookPrice() {
		return bookPrice;
	}

	public void setBookPrice(float bookPrice) {
		this.bookPrice = bookPrice;
	}

	public Book(String id, String bookName, float bookPrice) {
		super();
		this.id = id;
		this.bookName = bookName;
		this.bookPrice = bookPrice;
	}

	public Book() {

	}

}

4.book.xml


<?xml version="1.0" encoding="UTF-8"?>
<bookTest>
    <book id = "1">
        <name>thinking in java</name>
        <price>85.5</price>
        <test>Yellow Test</test>
    </book>
    <book id = "2">
        <name>Spring in Action</name>
        <price>39.0</price>
    </book>
    <Test>
    </Test>
</bookTest>


5.小结:


/*
 * 
 * Dom 解析过程
 * 1.通过 Element bookElement = (Element) bookNodes.item(i); 获取根节点
 * 2.通过 NodeList childNodeList = bookElement.getChildNodes(); 获取子节点
 * 		1)子节点包含"#text" 文本 和 节点元素
 * 		2)这里的节点元素不包含节点的关闭元素 比如 </name> 只包含开始标签元素 比如<name>
 * 3.通过判断 if (childNodeList.item(j).getNodeType() == Node.ELEMENT_NODE) 是否为真来确定是不是节点元素
 * 		1)在 Node.class 中定义  public static final short ELEMENT_NODE              = 1;
 * 		  比如这里 <test> 元素返回的为 1 而 文本返回的为 3 可以通过下列语句测试
 * 					System.out.println("childNodeList.item(0).getNodeType() is:"+childNodeList.item(0).getNodeType());
 * 4.如果是结点元素,通过 if ("name".equals(childNodeList.item(j).getNodeName())) 判断他是否是 <name> 结点 
 * 5.如果是<name> 结点 通过 book.setBookName(childNodeList.item(j).getFirstChild().getNodeValue());获取节点文本,并设置
 * 
 * 
 * 补充:
 * 解析器物理查找:
 * 1.查找 <bookTest> 根节点
 * 2.查找根节点后的 子节点1 <book>
 * 3.查找 子节点1 后的文本
 * 4.查找 文本后的 <name>
 * 5.查找<name> 后的文本
 * 6.查找<price> 节点
 * 7.查找<price> 节点后的文本
 * 8.查找<test> 节点
 * 9.查找<test> 后的文本
 * 
 * 10.然后继续查找 子节点2
 * 11.如此下去(可参考打印结果)
 * 
 * 
 * 调用 Dom 解析
 * 1.创建 DocumentBuilderFactory 对象
 * DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 * 2.从 DoccumentBuilderFactory 对象中获取一个 DocumentBuilder 对象
 * builder = factory.newDocumentBuilder();
 * 3.使用 DocumentBulider 对象将 XML 文件输入流转化为一个 Document 对象
 * document = builder.parse(inputStream);
 * 
 * 读取 XML 的方式
 * 1.通过 Java IO 流
 * FileInputStream input = new FileInputStream("D:\\book.xml");
 * Document doc = builder.parse(input);
 * 
 * 2.用过文件方式读取
 * File file = new File("D:\\book.xml");
 * Document doc = builder.parse(file);
 * 
 * 3.通过一个 URL 方式读取
 * URL u = new UPL("http://java.sun.com/index.html");
 * Document doc = builder.parse(u);
 * 
 * 这里使用的是第一种
 * */

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值