DOM解析XML

import java.io.IOException;

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;

import com.sun.org.apache.xerces.internal.impl.xs.dom.DOMParser;


public class DOMParserTest {
	
	public static void main(String[] args) {
		parseXMLFile("student.xml");
	}
	
	public static void parseXMLFile(String fileName){
		//构造DOM解析器的实例
		DOMParser parser = new DOMParser();
		//开始解析文档,将XML文件转换成DOM树存入内存
		try {
			parser.parse(fileName);
			//获得Document对象
			Document doc = parser.getDocument();
			//获得root节点
			Element root = doc.getDocumentElement();
//System.out.println(root.getNodeName());
			//获得子节点列表
			NodeList listStudent = root.getElementsByTagName("student");
			for (int i = 0; i < listStudent.getLength(); i++) {
				//获得当前student元素
				Element elmtStudent = (Element)listStudent.item(i);
				NodeList pro = elmtStudent.getElementsByTagName("name");
				Node node = pro.item(0);
				System.out.println(node.getNodeValue());
			}
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

 

XML文件
<?xml version="1.0" encoding="UTF-8"?>
<StudentInfo>
	<student>
		<name>张三</name>
		<sex>男</sex>
		<lesson>
			<lessonName>Spring</lessonName>
			<lessonScore>85</lessonScore>
		</lesson>
		<lesson>
			<lessonName>Ajax</lessonName>
			<lessonScore>86</lessonScore>
		</lesson>
	</student>
	<student>
		<name>李四</name>
		<sex>女</sex>
		<lesson>
			<lessonName>Struts</lessonName>
			<lessonScore>87</lessonScore>
		</lesson>
		<lesson>
			<lessonName>Hibernate</lessonName>
			<lessonScore>88</lessonScore>
		</lesson>
	</student>
</StudentInfo>
 

你可能感兴趣的:(spring,Ajax,xml,Hibernate,struts)