dom解析xml






	
		张瑞
		24
		
	
	
		胡黎明
		24
		
	








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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomTest {
	public static void main(String[] args) throws Exception{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse("Students.xml");
		NodeList nodeList = document.getElementsByTagName("Students");
		Node node = nodeList.item(0);
		NodeList childNodes = node.getChildNodes();
		System.out.println(childNodes.getLength());
	}
}

dom解析xml的步骤:

1.新建解析工厂

2.新建解析器

3.解析文件

4.形成dom树

5.获取根节点

6.拿到根节点的所有子节点

dom解析xml时会包括空格,所以上述的结果是5

xml:基于XML树结构     比较耗资源
适用于多次访问XML


for(int i=0;i"+attribute);
				NodeList childNodes2 = node2.getChildNodes();//拿到所有的Student的子节点   age  sex  name
				for(int j=0;j"+textContent);
					}
				}
			}
			System.out.println();
		}



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