使用XPath解析xml文档
jopen
11年前
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()); } }