使用XPath解析xml文档

本文详细介绍了如何使用XPath表达式从XML文档中选取特定元素,包括基本选取、属性筛选、位置筛选等,提供了丰富的示例代码帮助理解。
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class Xpather {
	public static void testXPath(String filePath) throws Exception {
		SAXBuilder sb = new SAXBuilder();
		Document doc = sb.build(new FileInputStream(filePath));
		Element root = doc.getRootElement(); //读取根节点
		//返回resume节点下的所有子节点
		XPath xPath = XPath.newInstance("/resume/*");
		//返回文档中所有preOccupation节点
		//XPath xPath = XPath.newInstance("//preOccupation");
		//返回/resume/wife/preOccupation这个节点
		//XPath xPath = XPath.newInstance("/resume/wife/preOccupation");
		//返回名字preOccupation有属性peroid的节点
		//XPath xPath = XPath.newInstance("/resume/wife/preOccupation[@period]");
		//返回文档中所有preOccupation节点,并且有属性period
		//XPath xPath = XPath.newInstance("//preOccupation[@period]");
		//返回名字为preOccupation属性period='5-18'的节点。
		//XPath xPath = XPath.newInstance("/resume/wife/preOccupation[@period='5-18']");
		//返回文档中所有preOccupation节点,并且文本内容为皇子
		//XPath xPath = XPath.newInstance("//preOccupation[text()='皇子']");
		List list = xPath.selectNodes(root);
		for (int i = 0; i < list.size(); i++) {
			Element e = (Element) list.get(i);
			System.out.println(e.getText());
		}
//		Element e2 = (Element) xPath.selectSingleNode(root);
//		System.out.println(e2.getText());
	}
}



转载于:https://my.oschina.net/u/1413786/blog/180634

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值