DOM解析XML文档步骤

看代码

package com.jelly.xml;

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

/**
 * dom解析XML
 * @author Jelly
 * date:2011/07/30
 */
public class Test {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		//step 1:或得dom解析器工厂(工作的作用用于创建具体的解析器)
		DocumentBuilderFactory abf = DocumentBuilderFactory.newInstance();
		//step 2:或得具体的dom解析器
		DocumentBuilder db = abf.newDocumentBuilder();
		//step 3:解析一个xml文档,或得一个Document对象(根节点)
		Document document = db.parse(new File("Test.xml"));
		NodeList list= document.getElementsByTagName("person");
		for(int i = 0;i<list.getLength();i++){
			Element ele = (Element) list.item(i);
			Node content =  ele.getElementsByTagName("name").item(0);
			System.out.println(content.getNodeValue());
			System.out.println(content.getNodeName());
			System.out.println(content.getFirstChild().getNodeValue());
		}
		//Element root =  document.getDocumentElement();
			
		//System.out.println(root.getNodeName());
	}
	
}

 

你可能感兴趣的:(dom解析xml)