Looping through data in JMeter and storing data to

2020-02-16 03:07发布

问题:

I have following data in XML response in JMeter:

<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>

suppose I have n number of such data, from the response of the XML file. I want to read value of "key". for eg. 1 I have to read "1" and store in a variable. For 1 such response i am reading it in XPath extractor and getting the correct value, but now I have to loop through it to get specified amount of key value in a variable. Suppose if I want 1000 such keys then I have to loop till 1000 times to get all the value in variables.

After getting that value in variables I have to used that value in another Sampler for eg: ${key1}

回答1:

Try to use Beanshell PostProcessor with beanshell/java code to extract all the values from xml-response and store they in variables or write to file.

  1. Attach Beanshell PostProcessor as child to the sampler which returns your xml response from above.
  2. Use the following code in PostProcessor (from external file or insert into "Script" field) to extract and save the keys:
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();
}

You can also save all the extracted keys into file and then read via CSV Data Set Config.

As well you can look into good article about Java XPath API with examples, in case if you meet any difficulties in script implementation.

Hope this helps.



回答2:

The above example code works for me however is missing one import:

import org.xml.sax.InputSource;

As the line:

InputSource is = new InputSource(new StringReader(result.getResponseDataAsString()));

requires InputSource to be imported.

After that it works perfectly for me.



回答3:

After getting the data, add a BeanShell PostProcessor element. Use the code below to write the variables to a file:

name = vars.get("name");
email = vars.get("email");

log.info(email);  // if you want to log something to jmeter.log file

// Pass true if you want to append to existing file
// If you want to overwrite, then don't pass the second argument
f = new FileOutputStream("/my/file/path/result.csv", true);
p = new PrintStream(f); 
this.interpreter.setOut(p); 
print(name + "," + email);
f.close();


回答4:

The selected answer seems to be a complicated way of just doing an xpath extraction using:

//serviceResponse/details/key/text()

Almost the same as your own xpath, except it finds all elements, not just the first (by simply removing the array reference []).

This will place all the found keys into variables called key_? where ? is an incrementing integer from key_1.

You can find how many variables were extracted from variable key_matchNr.

The complicated version above is different in that it will start at key_0.

Now how to iterate over this list is another matter, if that is what you need to do.



标签: xml xpath jmeter