java分享第十七天-01(封装操作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");
    }
} 



原文地址:https://www.cnblogs.com/tiancy/p/6065448.html