java XML解析之XPath解析

本文介绍了一种使用Java实现XML文件解析的方法,并通过XPath选取指定节点。具体步骤包括实例化DocumentBuilderFactory与XPath对象,解析XML文件,获取所需节点数据,并将数据存储到自定义Java类中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
		}
		
	}
}

运行结果:




JsoupXpath 是一款纯Java开发的使用xpath解析html的解析器,xpath语法分析与执行完全独立,html的DOM树生成借助Jsoup,故命名为JsoupXpath.为了在java里也享受xpath的强大与方便但又苦于找不到一款足够强大的xpath解析器,故开发了JsoupXpath。JsoupXpath的实现逻辑清晰,扩展方便,支持几乎全部常用的xpath语法.http://www.cnblogs.com/ 为例 "//a/@href"; "//div[@id='paging_block']/div/a[text()='Next >']/@href"; "//div[@id='paging_block']/div/a[text()*='Next']/@href"; "//h1/text()"; "//h1/allText()"; "//h1//text()"; "//div/a"; "//div[@id='post_list']/div[position()1000]/div/h3/allText()"; //轴支持 "//div[@id='post_list']/div[self::div/div/div/span[@class='article_view']/a/num()>1000]/div/h3/allText()"; "//div[@id='post_list']/div[2]/div/p/preceding-sibling::h3/allText()"; "//div[@id='post_list']/div[2]/div/p/preceding-sibling::h3/allText()|//div[@id='post_list']/div[1]/div/h3/allText()"; 在这里暂不列出框架间的对比了,但我相信,你们用了会发现JsoupXpath就是目前市面上最强大的的Xpath解析器。 快速开始 如果不方便使用maven,可以直接使用lib下的依赖包跑起来试试,如方便可直接使用如下dependency(已经上传至中央maven库,最新版本0.1.1):    cn.wanghaomiao    JsoupXpath    0.1.1 依赖配置好后,就可以使用如下例子进行体验了!String xpath="//div[@id='post_list']/div[./div/div/span[@class='article_view']/a/num()>1000]/div/h3/allText()";String doc = "..."; JXDocument jxDocument = new JXDocument(doc); List<Object> rs = jxDocument.sel(xpath); for (Object o:rs){     if (o instanceof Element){             int index = ((Element) o).siblingIndex();             System.out.println(index);     }     System.out.println(o.toString()); } 其他可以参考 cn.wanghaomiao.example包下的例子 语法 支持标准xpath语法(支持谓语嵌套),支持全部常用函数,支持全部常用轴,去掉了一些标准里面华而不实的函数和轴,下面会具体介绍。语法可以参考http://www.w3school.com.cn/xpath/index.asp 关于使用Xpath的一些注意事项 非常不建议直接粘贴Firefox或chrome里生成的Xpa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值