简体   繁体   中英

Jmeter - find with regex and replace part of XML body using groovy

I'm trying to replace part an XML response data with something else. Here is an example:

    ?xml version="1.0" encoding="UTF-8"?>
<trustedDevices><trustedDevice><id>1942</id><name>BksQ9LKwWuNOHpn</name></trustedDevice><trustedDevice><id>1944</id><name>6f4srs4PkJk1j36</name></trustedDevice><trustedDevice><id>1943</id><name>7cGYVAlmQoXaVrf</name></trustedDevice></trustedDevices>

I'm trying to get all the <name>(.+?)<\\/name> data and replace it with something else (timestamp or random string)

so far, my groovy post processor code looks like this:

String trustedDevices = prev.getResponseDataAsString()

log.info('Response: ' + trustedDevices)
def nameFind = "/<name>(.+?)<\/name>/"
def newTrustedDevices = trustedDevices.replaceAll(nameFind, "test")

log.info('New response: ' + newTrustedDevices)

Unfortunately it seems that replaceAll requires String or Long to work, and won't work with regex.

你正则表达式只需要一个正确的转义:

def nameFind = "<name>(.+?)<\\/name>"

Replacing values in XML using regular expressions is not the best option as it will be fragile and very sensitive to any markup change.

I would suggest going for Groovy's XML parsing capabilities instead

Example code:

def trustedDevices = new XmlSlurper().parseText(prev.getResponseDataAsString())
trustedDevices.trustedDevice.findAll().each {
    it.name = 'test'
}
def newTrustedDevices = new StreamingMarkupBuilder().bind { mkp.yield trustedDevices }.toString()

More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM