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