在java中使用dom解析xml

dom是个功能强大的解析工具,适用于小文档

为什么这么说呢?因为它会把整篇xml文档装载进内存中,形成一颗文档对象树

总之听起来怪吓人的,不过使用它来读取点小东西相对Sax而言还是挺方便的

至于它的增删操作等,我是不打算写了,在我看教程的时候我就差点被那代码给丑到吐了

也正因为如此,才有后来那些jdom和dom4j等工具的存在……

不多说,直接上代码

Dom解析示例

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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 Demo {

	public static void main(String[] args) throws Exception {
		//创建解析器工厂实例,并生成解析器
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		//创建需要解析的文档对象
		File f = new File("books.xml");
		//解析文档,并返回一个Document对象,此时xml文档已加载到内存中
		//好吧,让解析来得更猛烈些吧,其余的事就是获取数据了
		Document doc = builder.parse(f);
		
		//获取文档根元素
		//你问我为什么这么做?因为文档对象本身就是树形结构,这里就是树根
		//当然,你也可以直接找到元素集合,省略此步骤
		Element root = doc.getDocumentElement();
		
		//上面找到了根节点,这里开始获取根节点下的元素集合
		NodeList list = root.getElementsByTagName("book");
		
		for (int i = 0; i < list.getLength(); i++) {
			//通过item()方法找到集合中的节点,并向下转型为Element对象
			Element n = (Element) list.item(i);
			//获取对象中的属性map,用for循环提取并打印
			NamedNodeMap node = n.getAttributes();
			for (int x = 0; x < node.getLength(); x++) {
				Node nn = node.item(x);
				System.out.println(nn.getNodeName() + ": " + nn.getNodeValue());
			}
			//打印元素内容,代码很纠结,差不多是个固定格式
			System.out.println("title: " +n.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
			System.out.println("author: " + n.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
			System.out.println();
		}
	}

}

 输出结果:

 

posted @ 2013-05-03 18:26  Nerxious  阅读(6663)  评论(0编辑  收藏  举报