循环遍历JMeter中的数据并存储要在其他采样器中使用的数据


问题内容

我在JMeter的XML响应中有以下数据:

<details>
<srNo>1</srNo>
<key>123</key>
<Name>Inspector</piName>
<age>89</age>
<country>India</country>
</details>
....................................
...................................
<details>
<srNo>1</srNo>
<key>123</key>
<Name>Inspector</piName>
<age>89</age>
<country>America</country>
</details>

假设我从XML文件的响应中获得了n个这样的数据。我想读取“键”的值。例如 1我必须读取“
1”并存储在变量中。对于1这样的响应,我正在XPath提取器中读取它并获取正确的值,但是现在我必须遍历它以获取变量中指定数量的键值。假设如果我想要1000个这样的键,那么我必须循环直到1000次才能获取变量中的所有值。

在变量中获得该值后,我必须在另一个Sampler中使用该值,例如:$ {key1}


问题答案:

尝试将Beanshell
PostProcessor
Beanshell
/ java代码一起使用,以从xml响应中提取所有值并将它们存储在变量中或写入文件中。

  1. 将Beanshell PostProcessor作为子项附加到采样器,该采样器从上面返回xml响应。
  2. 在PostProcessor中使用以下代码(从外部文件或插入“脚本”字段)来提取和保存密钥:
    import java.io.*;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;

    import org.apache.jmeter.samplers.SampleResult;

    // set here your xpath expression (to extract EVERY key, not any separate one)
    String xpathExpr = "//serviceResponse/details/key/text()";

    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // access result of parent sampler via "ctx" BeanShell variable        
        SampleResult result = ctx.getPreviousResult();
        InputSource is = new InputSource(new StringReader(result.getResponseDataAsString()));
        Document doc = builder.parse(is);

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile(xpathExpr);
        NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);

        // extract all the keys in loop
        for (int i = 0; i < nodes.getLength(); i++) {
            String key = nodes.item(i).getNodeValue();

            System.out.println(key);

            // save extracted key as separate jmeter variables        
            String keyName = "key_" + Integer.toString(i);
            vars.put(keyName,key);
        }
    } catch (Exception ex) {
        IsSuccess = false;
        log.error(ex.getMessage());
        ex.printStackTrace();
    }

您还可以将所有提取的密钥保存到文件中,然后通过CSV数据集配置读取。

此外,如果遇到脚本实现方面的任何困难,您也可以阅读有关Java XPath
API的优秀文章
和示例。

希望这可以帮助。