DOM解析XML——打印所有元素的名字(迭代)

import java.io.InputStream;

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

import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMDemo {
	
	Document document = null;
	
	@Before
	public void init() throws Exception {
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		InputStream xmlFile = Thread.currentThread().getContextClassLoader().getResourceAsStream("contacts.xml");
		document = documentBuilder.parse(xmlFile );
		System.out.println(document+"init");
	}

//2、遍历所有元素节点:打印所有元素的名字
	@Test
	public void test2() throws Exception {
		Element root = document.getDocumentElement();
		doGetName(root);
	}
	
	public void doGetName(Node e){
		System.out.println(e.getNodeName());
		NodeList nodes = e.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			Node childNode =  nodes.item(i);
			if("#text".equals(childNode.getNodeName())){
				continue;
			}
			doGetName(childNode);
		}
	}
	
}


你可能感兴趣的:(java学习笔记)