作自動化測試的人,都應該對XPATH很熟悉了,可是在用JAVA解析XML時,咱們一般是一層層的遍歷進去,這樣的代碼的侷限性很大,也不方便,因而咱們結合一下XPATH,來解決這個問題。
所須要的JAR包:
dom4j.jar
jaxen.jar
xmlbeans.jar
具體的代碼以下:dom
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"); } }