java XML解析之XPath解析

1.实例化DocumentBuilderFactory对象,该对象帮助创建DocumentBuilder对象,用于解析。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//实例化DocumentBuilderFactory对象
DocumentBuilder bulider = dbf.newDocumentBuilder();

2.用DocumentBuilder对象进行解析

Document    doc=    bulider.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML/Student.xml"));

3.实例化Xpath对象

PathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象,帮助创建XPath对象

 XPath xpath = factory.newXPath();

4.获取XML文件的节点,进行操作

XPathExpression compile = xpath.compile("//student");//选取student节点

NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);//获取student节点的所有节点

例子

1.创建XML文件



	
		"张三"
		
		1003
	
	
	
		"李四"
		
		1004
	
	
	
		"张五"
		
		25	
	

2.创建Students类,将解析的数据存储来该类的对象

package MyXMl;

public class Students {
	private int id;
	private int socre;
	private String name;
	private String sex;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getSocre() {
		return socre;
	}
	public void setSocre(int socre) {
		this.socre = socre;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Students [id=" + id + ", socre=" + socre + ", name=" + name + ", sex=" + sex + "]";
	}	
}

3.主类进行解析测试:

package MyXMl;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

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

public class XPathParse {
	public static void main(String[] args) throws Exception{
		List list = new ArrayList();//解析出来的数据用Stundent对象存储,用集合存储该对象
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//实例化DocumentBuilderFactory对象
		DocumentBuilder bulider = dbf.newDocumentBuilder();
		Document doc = bulider.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML/Student.xml"));
		
		XPathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象
		XPath xpath = factory.newXPath();
		
		XPathExpression compile = xpath.compile("//student");//选取student节点
		NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);//获取student节点的所有节点
		for(int i=0;i

运行结果:




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