使用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());
	}
}
相关文章
相关标签/搜索