从同一个标签多次获取值
Get values multiple times from same tags
我使用 SoapUI 来处理 SOAP 请求。我尝试在同一个 SOAP 响应上多次匹配同一个正则表达式,它多次包含相同的标签 <ns12:AmountID>
,我需要所有的值。我以这种方式在 Groovy
脚本中使用正则表达式:
String numberToGet = reger.getNthMatch(/<ns12:AmountID>(\d+)<\/ns12:AmountID>/, 0);
我怎样才能使输出值不同?
XPath 或 Groovy 的 GPath 几乎总是比使用正则表达式更好的在 XML 文档中查找内容的方法。例如:
import groovy.util.XmlSlurper
def amountIDstring = '''
<root xmlns:ns12="http://www.w3.org/TR/html4/">
<ns12:AmountID>1230</ns12:AmountID>
<ns12:AmountID>460</ns12:AmountID>
<ns12:AmountID>123</ns12:AmountID>
<ns12:AmountID>670</ns12:AmountID>
<ns12:AmountID>75</ns12:AmountID>
<ns12:AmountID>123</ns12:AmountID>
</root>
'''
def amountIDtext = new XmlSlurper().parseText(amountIDstring)
def numberToGet = amountIDtext.'**'.findAll{node -> node.name() == 'AmountID'}*.text()
numberToGet.each{ println "Amount ID = ${it}"}
这个returns:
Amount ID = 1230
Amount ID = 460
Amount ID = 123
Amount ID = 670
Amount ID = 75
Amount ID = 123
Result: [1230, 460, 123, 670, 75, 123]
你可以用下面的代码得到这个,它很容易理解和处理XML。
另外我觉得语法比 XMLSlurper 更容易记住。从任何 XML
中检索值的最佳方法之一
def groovyUtils=new com.eviware.soapui.support.GroovyUtils(context)
// Cosidering your soap request name is **SampleRequest**
def respsone=groovyUtils.getXmlHolder("SampleRequest#Response")
def AmountId=respsone.getNodeValues("//*:AmountID")
// Printing as a list
log.info AmountId.toString()
// Printing as individual item from Array
for(def var in AmountId)
log.info var
下面是输出
我使用 SoapUI 来处理 SOAP 请求。我尝试在同一个 SOAP 响应上多次匹配同一个正则表达式,它多次包含相同的标签 <ns12:AmountID>
,我需要所有的值。我以这种方式在 Groovy
脚本中使用正则表达式:
String numberToGet = reger.getNthMatch(/<ns12:AmountID>(\d+)<\/ns12:AmountID>/, 0);
我怎样才能使输出值不同?
XPath 或 Groovy 的 GPath 几乎总是比使用正则表达式更好的在 XML 文档中查找内容的方法。例如:
import groovy.util.XmlSlurper
def amountIDstring = '''
<root xmlns:ns12="http://www.w3.org/TR/html4/">
<ns12:AmountID>1230</ns12:AmountID>
<ns12:AmountID>460</ns12:AmountID>
<ns12:AmountID>123</ns12:AmountID>
<ns12:AmountID>670</ns12:AmountID>
<ns12:AmountID>75</ns12:AmountID>
<ns12:AmountID>123</ns12:AmountID>
</root>
'''
def amountIDtext = new XmlSlurper().parseText(amountIDstring)
def numberToGet = amountIDtext.'**'.findAll{node -> node.name() == 'AmountID'}*.text()
numberToGet.each{ println "Amount ID = ${it}"}
这个returns:
Amount ID = 1230
Amount ID = 460
Amount ID = 123
Amount ID = 670
Amount ID = 75
Amount ID = 123
Result: [1230, 460, 123, 670, 75, 123]
你可以用下面的代码得到这个,它很容易理解和处理XML。
另外我觉得语法比 XMLSlurper 更容易记住。从任何 XML
中检索值的最佳方法之一def groovyUtils=new com.eviware.soapui.support.GroovyUtils(context)
// Cosidering your soap request name is **SampleRequest**
def respsone=groovyUtils.getXmlHolder("SampleRequest#Response")
def AmountId=respsone.getNodeValues("//*:AmountID")
// Printing as a list
log.info AmountId.toString()
// Printing as individual item from Array
for(def var in AmountId)
log.info var
下面是输出