【问题标题】:Get values multiple times from same tags从同一标签多次获取值
【发布时间】:2025-12-30 04:35:09
【问题描述】:

我使用 SoapUI 来处理 SOAP 请求。我尝试在同一个 SOAP 响应上多次匹配同一个正则表达式,它包含相同的标签,<ns12:AmountID> 多次,我需要所有的值。我以这种方式在Groovy 脚本中使用正则表达式:

String numberToGet = reger.getNthMatch(/<ns12:AmountID>(\d+)<\/ns12:AmountID>/, 0);

如何区分输出值?

【问题讨论】:

    标签: soap groovy soapui


    【解决方案1】:

    您可以使用以下易于理解和处理 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
    

    下面是输出

    【讨论】:

      【解决方案2】:

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

      这会返回:

      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]
      

      【讨论】:

        最近更新 更多