Samant
Samant

Reputation: 92

Jmeter value to variable in string

How do i replace a variable defined in a file (a.xml) after the file is read into Jmeter ? eg. a.xml has a content.

<Shipment Action="MODIFY" OrderNo="${vOrderNo}" >

The entire file is read into a string using str_Input=${__FileToString(/a.xml)}

In the Jmx file, a http Request is made to get output from a webservice as Using Xpath Extractor the value of OrderNo is read into a Variable vOrderNo.

Now, wanted to use the value of variable vOrderNo in the str_Input.. ? How do i ?

Upvotes: 0

Views: 8215

Answers (1)

Aliaksandr Belik
Aliaksandr Belik

Reputation: 12873

You can easily achieve this using beanshell (~java) code from any jmeter's sampler which allows beanshell code execution - BeanShell Sampler e.g..

The following works:


import java.io.*;

try
{
    // reading file into buffer
    StringBuilder data = new StringBuilder();
    BufferedReader in = new BufferedReader(new FileReader("d:\\test.xml"));

    char[] buf = new char[1024];
    int numRead = 0;
    while ((numRead = in.read(buf)) != -1) {
    data.append(buf, 0, numRead);
    }
    in.close();

    // replacing stub with actual value
    String vOrderNo = vars.get("vOrderNo");
    String temp = data.toString().replaceAll("\\$\\{vOrderNo\\}", vOrderNo);

    // writing back into file
    Writer out = new BufferedWriter(new FileWriter("d:\\test.xml"));
    out.write(temp);
    out.close();
}
catch (Exception ex) {
    IsSuccess = false;
    log.error(ex.getMessage());
    System.err.println(ex.getMessage());
}
catch (Throwable thex) {
    System.err.println(thex.getMessage());
}

This code doesn't require read file into string via ${__FileToString(...)}.
As well, you can combine both methods.

Upvotes: 1

Related Questions