dom4j操作jmx文件的封装(二)

该代码示例演示了如何利用DOM4J库在JMeter的JMX文件中指定位置插入HTTPSamplerProxy元素,以创建一个新的HTTP请求。通过读取现有JMX模板文件,修改DOM树,然后写入新的JMX文件,实现了动态生成测试计划的能力。主要涉及DOM4J的Element、XPath和XMLWriter等操作。
摘要由CSDN通过智能技术生成

概述:实现了dom4j在指定位置进行进行追加元素,并生成新的jmx文件。

代码如下:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;



public class TestM2 {
        static String  hashTree_xpath="/jmeterTestPlan/hashTree/hashTree/hashTree";
  public static void  main(String [] args) throws DocumentException {
	 
	  SAXReader reader = new SAXReader();
	  String  httpmoduleJmxPath=System.getProperty("user.dir")+"/resources/httpmodule.jmx";
	  String  httpmoduleJmxPath2=System.getProperty("user.dir")+"/resources/httpmodule2.jmx";
	  
      Document document = reader.read(new File(httpmoduleJmxPath));
      
    //通过模板,将数据放入document对象中
      creatJmx( document,"http://www.baidu.com/user/login.html","www.baidu.com","80","https","/user/login.html","GET") ;
      outJmx( document,httpmoduleJmxPath2) ;//输出追加后的新jmx文件
         }
  
  //通过xpath定位节点,并修改dom树
  public static void chengNodeValue(Element root,String xpath,String newValue) {
 	 
      Node node=  root.selectSingleNode(xpath);
      node.setText(newValue);
 	 
  }
  //document当前文档对象,jmxPath 为jmx文件路径
  public static void outJmx(Document document,String jmxPath ) {
	  XMLWriter output;
	try {
		   output = new XMLWriter(new FileWriter(jmxPath));
		   output.write(document);
	      output.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
      
  }
  /**
   * @author liujian
   * 参数说明
   * @param httpmoduleJmxPath jmx 模板位置
   * @param siteAllPath 站点全路径用来设置HTTPSamplerProxy的名字,这样不会重名
   * @param  domain 域名
   * @param  port 端口
   * @param  protocol   协议头 http或者https
   * @param  path 路径,就是端口后面的路径
   * @param method  请求方法get、 post
   * **/
  

  public static void  creatJmx(Document document,String  siteAllPath,String domain,String port,String protocol,String path,String method) throws DocumentException {
	
      Element root =document.getRootElement();
       
      Element node=  (Element) root.selectSingleNode(hashTree_xpath);
    /*说明
     * 获取元素列表,这样可以指定位置放入创建的元素,如果直接用node.addElement()会直接追加到末尾,
     * 但是jemeter它不识别,会报打不开的错误。
     */
       List eleList=    node.elements(); 
      
  
      Element hashTree = DocumentHelper.createElement("hashTree");//创建一个元素

      eleList.add(1, hashTree);//如果原来1的位置有其他元素,放心不会覆盖掉原来的元素,原来1位置上的元素以及它后面对元素位置会自动往后移一位
      
    
      Element HTTPSamplerProxy=   DocumentHelper.createElement("HTTPSamplerProxy")
      .addAttribute("guiclass", "HttpTestSampleGui")
      .addAttribute("testclass", "HTTPSamplerProxy")
      .addAttribute("testname", siteAllPath)
      .addAttribute("enabled", "true");
      Element  elementProp= HTTPSamplerProxy.addElement("elementProp")
      .addAttribute("name", "HTTPsampler.Arguments")
      .addAttribute("elementType", "Arguments")
      .addAttribute("guiclass", "HTTPArgumentsPanel")
      .addAttribute("testclass", "Arguments")
      .addAttribute("testname", "用户定义的变量")
      .addAttribute("enabled", "true");
      Element  collectionProp= elementProp.addElement("collectionProp").addAttribute("name", "Arguments.arguments");
      
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.domain").setText(domain);
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.port").setText(port);
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.protocol").setText(protocol);
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.contentEncoding").setText("utf-8");
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.path").setText(path);
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.method").setText(method);
      HTTPSamplerProxy.addElement("boolProp").addAttribute("name", "HTTPSampler.follow_redirects").setText("true");
      HTTPSamplerProxy.addElement("boolProp").addAttribute("name", "HTTPSampler.auto_redirects").setText("false");
      HTTPSamplerProxy.addElement("boolProp").addAttribute("name", "HTTPSampler.use_keepalive").setText("true");
      HTTPSamplerProxy.addElement("boolProp").addAttribute("name", "HTTPSampler.DO_MULTIPART_POST").setText("false");
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.embedded_url_re").setText("false");;
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.connect_timeout");
      HTTPSamplerProxy.addElement("stringProp").addAttribute("name", "HTTPSampler.response_timeout");
      eleList.add(2, HTTPSamplerProxy);//如果原来2的位置有其他元素,放心不会覆盖掉原来的元素,原来的2位置上的元素以及它后面对元素位置会自动往后移一位


  }
  
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
dom4j,jsoup,jdom,w3cdom,xstream使用代码工程 package ivyy.taobao.com.dom4j; import ivyy.taobao.com.entity.Address; import ivyy.taobao.com.entity.Location; import ivyy.taobao.com.entity.Point; import ivyy.taobao.com.entity.Pois; import ivyy.taobao.com.utils.IoUtils; import ivyy.taobao.com.utils.UrlUtils; import ivyy.taobao.com.utils.Dom4jUtils; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.jsoup.Jsoup; import org.jsoup.select.Elements; /** *@Date:2015-1-6 *@Author:liangjilong *@Email:jilongliang@sina.com *@Version:1.0 *@Description: */ @SuppressWarnings("all") public class Dom4jTest2 { public static void main(String[] args)throws Exception { //String filepath="D:/"+System.currentTimeMillis()+".xml"; String filepath="D:/test/map1.xml"; File f=new File(filepath); if(!f.exists()){ f.createNewFile(); } //List<Pois> list=getReaderXml("URL"); List<Pois> list=getReaderXml("FILE"); org.dom4j.Document doc=createAsXML(list); IoUtils.write(doc.asXML(),filepath); //格式化 Dom4jUtils.formatAsXml(doc); } /**** * 组装成一个xml * @param list * @return * @throws Exception */ private static org.dom4j.Document createAsXML(List<Pois> list) throws Exception{ org.dom4j.Document doc=DocumentHelper.createDocument(); Element root=doc.addElement("GeocoderSearchResponse");//根 root.addElement("status").setText("0");//status for (Iterator iterator = list.iterator(); iterator.hasNext();) { Pois pois = (Pois) iterator.next(); Element result=root.addElement("result");//result List<Location> listLoc=pois.getLocations(); Element location=result.addElement("location");//location for (Iterator iterator2 = listLoc.iterator(); iterator2.hasNext();) { Location locObj = (Location) iterator2.next(); location.addElement("lat").setText(locObj.getLat()+"");//lat location.addElement("lng").setText(locObj.getLng()+"");//lat result.addElement("formatted_address").setText(locObj.getFormattedAddress()+"");//formatted_address result.addElement("business").setText(locObj.getBusiness()+"");//business } List<Address> listAdd=pois.getAddress(); Element comp=result.addElement("addressComponent");//addressComponent for (Iterator iterator3 = listAdd.iterator(); iterator3.hasNext();) { Address address = (Address) iterator3.next(); comp.addElement("streetNumber").setText(address.getStreetNumber()+"");//streetNumber comp.addElement("street").setText(address.getStreet()+"");//street comp.addElement("district").setText(address.getDistrict()+"");//district comp.addElement("city").setText(address.getCity()+"");//city comp.addElement("province").setText(address.getProvince()+"");//province comp.addElement("cityCode").setText(address.getCityCode()+"");//cityCode } Element poi=result.addElement("pois").addElement("poi"); poi.addElement("addr").setText(pois.getAddr());//addr poi.addElement("distance").setText(pois.getDistance());//distance poi.addElement("name").setText(pois.getName());//name poi.addElement("poiType").setText(pois.getPoiType());//poiType poi.addElement("tel").setText(pois.getTel());//tel poi.addElement("zip").setText(pois.getZip());//zip List<Point> listPoint=pois.getPoints(); Element point=poi.addElement("point"); for (Iterator iterator4 = listPoint.iterator(); iterator4.hasNext();) { Point p = (Point) iterator4.next(); point.addElement("x").setText(p.getX()+""); point.addElement("y").setText(p.getY()+""); } } return doc; } /** * Dom4j(SAX)读取xml数据(解析) * @param params * @throws Exception */ private static List<Pois> getReaderXml(String flg) throws Exception{ String fromRead=Dom4jTest2.class.getClassLoader().getResource("xml/map1.xml").getPath(); List<Pois> list=new ArrayList<Pois>(); SAXReader saxReader = new SAXReader(); org.dom4j.Document document=null; //从api上面解析 if(flg.equals("URL")){ String url = UrlUtils.getBaiduMapUrl("你的key", "39.983424,116.322987", "xml"); document = saxReader.read(url); //从文件上面的xml解析 }else if(flg.equals("FILE")){ document = saxReader.read(new File(fromRead)); } Element resultEl = (Element)document.getRootElement().element("result"); Element poisEl=resultEl.element("pois");//pois节点 Element locationEl=resultEl.element("location");//location节点 Element addressEl=resultEl.element("addressComponent");//addressComponent节点 /*******从pois节点下面遍历多个poi节点*******/ for (Iterator<Element> poIter = poisEl.elementIterator("poi"); poIter.hasNext();) { Element element = (Element) poIter.next(); String addr = element.elementText("addr"); String distance = element.elementText("distance"); String name = element.elementText("name"); String poiType = element.elementText("poiType"); String tel =(element.elementText("tel")==""?"":element.elementText("tel")); String zip =(element.elementText("zip")==""?"":element.elementText("zip")); Pois poi=new Pois(); poi.setAddr(addr); poi.setDistance(distance); poi.setName(name); poi.setPoiType(poiType); poi.setTel(tel); poi.setZip(zip); List<Location> listLoc=new ArrayList<Location>(); /************Location***************************/ String business=resultEl.elementText("business"); String formatted_address=resultEl.elementText("formatted_address"); String lat = locationEl.elementText("lat"); String lng = locationEl.elementText("lng"); Location location=new Location(); location.setBusiness(business); location.setFormattedAddress(formatted_address); location.setLat(lat); location.setLng(lng); listLoc.add(location); poi.setLocations(listLoc); List<Address> listAddr=new ArrayList<Address>(); /************Address***************************/ Address address=new Address(); String streetNumber=(addressEl.elementText("streetNumber")==""?"":addressEl.elementText("streetNumber")); String street=(addressEl.elementText("street")==""?"":addressEl.elementText("street")); String district=(addressEl.elementText("district")==""?"":addressEl.elementText("district")); String city=(addressEl.elementText("city")==""?"":addressEl.elementText("city")); String province=(addressEl.elementText("province")==""?"":addressEl.elementText("province")); String direction=(addressEl.elementText("direction")==""?"":addressEl.elementText("direction")); String distancez=(addressEl.elementText("distance")==""?"":addressEl.elementText("distance")); address.setStreetNumber(streetNumber); address.setStreet(street); address.setCity(city); address.setDistrict(district); address.setDirection(direction); address.setDistance(distancez); address.setProvince(province); listAddr.add(address); poi.setAddress(listAddr); list.add(poi); } return list; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值