java結合XPATH解析XML


做自動化測試的人,都應該對XPATH很熟悉了,但是在用JAVA解析XML時,我們通常是一層層的遍歷進去,這樣的代碼的局限性很大,也不方便,於是我們結合一下XPATH,來解決這個問題。

所需要的JAR包:

dom4j.jar

jaxen.jar

xmlbeans.jar

具體的代碼如下:

public class ParseXml {	
	
	private String filePath;

	private Document document; 	
	
	public ParseXml(String filePath) {		
		this.filePath = filePath;
		this.load(this.filePath);
	}	
	
	private void load(String filePath){
		File file = new File(filePath);
		if (file.exists()) {
			SAXReader saxReader = new SAXReader();
			try {
				document = saxReader.read(file);
			} catch (DocumentException e) {		
				System.out.println("文件加載異常:" + filePath);				
			}
		} else{
			System.out.println("文件不存在 : " + filePath);
		}			
	}	
	
	public Element getElementObject(String elementPath) {
		return (Element) document.selectSingleNode(elementPath);
	}	
	
	@SuppressWarnings("unchecked")
	public List<Element> getElementObjects(String elementPath) {
		return document.selectNodes(elementPath);
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, String> getChildrenInfoByElement(Element element){
		Map<String, String> map = new HashMap<String, String>();
		List<Element> children = element.elements();
		for (Element e : children) {
			map.put(e.getName(), e.getText());
		}
		return map;
	}
	
	public boolean isExist(String elementPath){
		boolean flag = false;
		Element element = this.getElementObject(elementPath);
		if(element != null) flag = true;
		return flag;
	}

	public String getElementText(String elementPath) {
		Element element = this.getElementObject(elementPath);
		if(element != null){
			return element.getText().trim();
		}else{
			return null;
		}		
	}
	
	public static void main(String[] args) {
		
		ParseXml px = new ParseXml("config/TestBaidu.xml");
		List<Element> elements = px.getElementObjects("/*/testUI");
		
	}
	
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM