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文件

<?xml version="1.0" encoding="UTF-8"?>
<students>
	<student score="23">
		<name>"张三"</name>
		<sex>女</sex>
		<id>1003</id>
	</student>
	
	<student score="24">
		<name>"李四"</name>
		<sex>男</sex>
		<id>1004</id>
	</student>
	
	<student id="1005">
		<name>"张五"</name>
		<sex>男</sex>
		<score>25</score>	
	</student>

</students>

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 <Students>list = new ArrayList<Students>();//解析出来的数据用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<nodes.getLength();i++) {
			Students stu = new Students();
	          NodeList childNodes = nodes.item(i).getChildNodes(); //获取一个student节点所有的子节点,返回集合
	         //遍历所有子节点,获取节点的名称与数据,将其存与Students对象的属性进行匹配并存入到该对象
	          for(int j=0;j<childNodes.getLength();j++) {
	        	 Node node = childNodes.item(j);
	        	 if("name".equals(node.getNodeName())) {
	        		 stu.setName(node.getTextContent());
	        	 }
	        	 if("sex".equals(node.getNodeName())) {
	        		 stu.setSex(node.getTextContent());
	        	 }
	        	 if("id".equals(node.getNodeName())) {
	        		 stu.setId(Integer.parseInt(node.getTextContent()));
	        	 }
	        	 if("score".equals(node.getNodeName())) {
	        		 stu.setSocre(Integer.parseInt(node.getTextContent()));
	        	 }
	          }
	          //获取 student节点的属性,将其存与Students对象的属性进行匹配并存入到该对象
	          NamedNodeMap arr = nodes.item(i).getAttributes();
	          for(int k=0;k<arr.getLength();k++) {
	        	  Node ar = arr.item(k);
	        	  if("name".equals(ar.getNodeName())) {
		        		 stu.setName(ar.getTextContent());
		        	 }
		        	 if("sex".equals(ar.getNodeName())) {
		        		 stu.setSex(ar.getTextContent());
		        	 }
		        	 if("id".equals(ar.getNodeName())) {
		        		 stu.setId(Integer.parseInt(ar.getTextContent()));
		        	 }
		        	 if("score".equals(ar.getNodeName())) {
		        		 stu.setSocre(Integer.parseInt(ar.getTextContent()));
		        	 }
	          }
	          list.add(stu);
		}
		for(Students s:list) {//遍历输出测试
			System.out.println(s);
		}
		
	}
}

运行结果:




  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值