1 /** 2 * XPath获取属性值 3 * @param root 4 * @param xPath 5 * @return 6 */ 7 public static String getXPathAttributeValue(Element root, String xPath){ 8 XPathExpression<Attribute> pp = XPathFactory.instance().compile(xPath,Filters.attribute()); 9 return pp.evaluateFirst(root).getValue(); 10 } 11 12 /** 13 * XPath获取节点值 14 * @param root 主节点 15 * @param xPath XPath字符串 16 * @return 没有找到返回null 17 */ 18 public static String getXPathText(Element root, String xPath){ 19 XPathExpression<Text> pp = XPathFactory.instance().compile(xPath,Filters.text()); 20 return pp.evaluateFirst(root).getText(); 21 } 22 23 /** 24 * XPath获取节点 25 * @param root 主节点 26 * @param xPath XPath字符串 27 * @return 没有找到返回null 28 */ 29 public static Element getXPathNode(Element root, String xPath){ 30 XPathExpression<Element> pp = XPathFactory.instance().compile(xPath,Filters.element()); 31 return pp.evaluateFirst(root); 32 } 33 34 /** 35 * XPath获取节点集合 36 * @param root 主节点 37 * @param xPath XPath字符串 38 * @return XPath得到的节点集合 39 */ 40 public static List<Element> getXPathNodes(Element root, String xPath){ 41 XPathExpression<Element> pp = XPathFactory.instance().compile(xPath,Filters.element()); 42 return pp.evaluate(root); 43 }
JDom2的Xpath的获取关键在XPathExpression、XPathFactory身上.