本文共 2553 字,大约阅读时间需要 8 分钟。
我们也可以用xml来定义一个信息更为丰富的UIMap.xml文件,比如,额外还添加控件所属的页,控件的类型,然后解析构建一个XMLParser类来读取相应的值。
1 23 6 7 10
相应的解析xml的代码:
1 public static String getLocator(String locatorID){ 2 InputStream ins=Thread.currentThread().getContextClassLoader() 3 .getResourceAsStream(FileConstants.XMLFILE_NAME); 4 if(ins==null){ 5 System.out.println("Missing UIMap.xml file."); 6 return null; 7 } 8 9 DocumentBuilderFactory fac=DocumentBuilderFactory.newInstance();10 DocumentBuilder builder=null;11 try {12 builder = fac.newDocumentBuilder();13 } catch (ParserConfigurationException pce) {14 System.out.println("Failing to new DocumentBuilder for runtime exception.");15 throw new RuntimeException(pce);16 }17 18 Document xmlDoc=null;19 try {20 xmlDoc = builder.parse(ins);21 } catch (SAXException se) {22 System.out.println("Failing to parse xml file for runtime exception.");23 throw new RuntimeException(se);24 } catch (IOException ie) {25 System.out.println("Failing to parse xml file for runtime exception.");26 throw new RuntimeException(ie);27 }28 29 XPathFactory pathFac=XPathFactory.newInstance();30 XPath xpath = pathFac.newXPath();31 32 XPathExpression exp=null;33 try {34 exp = xpath.compile("UIMap/Object[@ID='"+locatorID+"']/Attributes");35 } catch (XPathExpressionException e) {36 System.out.println("Failing to get locator for :"+locatorID); 37 }38 Node node=null;39 try {40 node = (Node)exp.evaluate(xmlDoc, XPathConstants.NODE);41 } catch (XPathExpressionException e) {42 43 e.printStackTrace();44 }finally{45 try{46 if(ins!=null){47 ins.close();48 }49 }catch(Exception ex){50 System.out.println("Failing to load UIMap.xml for runtime exception.");51 throw new RuntimeException(ex);52 }53 }54 55 return node.getAttributes().getNamedItem("Locator").getNodeValue();56 }
测试代码:
1 selenium.type(UIMapParser.getLocator("UserName"), "seleniumtest");2 selenium.type(UIMapParser.getLocator("Password"), "seleniumtest");
注:转载需注明出处及作者。