使用XPath解析xml文檔

jopen 11年前發布 | 19K 次閱讀 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("http://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("http://preOccupation[@period]"); //返回名字為preOccupation屬性period='5-18'的節點。 //XPath xPath = XPath.newInstance("/resume/wife/preOccupation[@period='5-18']"); //返回文檔中所有preOccupation節點,并且文本內容為皇子 //XPath xPath = XPath.newInstance("http://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()); } }</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!