用于验证响应数据是否按升序排列的Groovy脚本

n9vozmp4  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(140)

我有一个SOAP响应,需要使用Groovy脚本来Assert行xml子级中的date参数是否以升序出现。
XML响应

<tree>
 <row>
  <id>123<id>
  <date>20220501</date>
 </row>
 <row>
  <id>242<id>
  <date>20220502</date>
 </row>
 <row>
  <id>125<id>
  <date>20220502</date>
 </row>
</tree>

请帮助我与groovy脚本的方法/脚本为相同的,我是一个初学者在这里。

zy1mlcev

zy1mlcev1#

带有日期(作为整数)比较简单SAX解析解决方案:

import javax.xml.parsers.SAXParserFactory
import javax.xml.streams.*
import org.xml.sax.*
import org.xml.sax.helpers.DefaultHandler

def xml = '''
<tree>
 <row>
  <id>123</id>
  <date>20220501</date>
 </row>
 <row>
  <id>242</id>
  <date>20220502</date>
 </row>
 <row>
  <id>125</id>
  <date>20220502</date>
 </row>
</tree>
'''

 class MyHandler extends DefaultHandler {

    int lastDate = -1
    def parsingDate = false
    def ordered = true

    void startElement(String namespace, String localname, String qname, Attributes atts){
        // enters into <date> tag
        parsingDate = (qname == 'date')
    }

    void characters(char[] ch, int start, int length){
        if (parsingDate ){
            // get date as int
            def date = new String(ch).substring(start,start+length) as int
            // comparison
            ordered &= (date >= lastDate )
            lastDate = date
            // else may be throw an exception
        }
    }

    void endElement(String uri, String localName, String qName) {
        // exit from date tag
        parsingDate = false
    }

}

def handler = new MyHandler()
def factory  = SAXParserFactory.newInstance()
def reader = factory.newSAXParser().XMLReader
reader.contentHandler = handler

reader.parse(new InputSource(new ByteArrayInputStream(xml.bytes)))

println handler.ordered
cidc1ykv

cidc1ykv2#

您应该能够利用XmlSlurper读入和访问XML。

def xmlStr = '''
  <tree>
    <row>
      <id>123</id>
      <date>20220501</date>
    </row>
    <row>
      <id>242</id>
      <date>20220502</date>
    </row>
    <row>
      <id>125</id>
      <date>20220502</date>
    </row>
  </tree>
'''

// parse the XML string so we can manipulate it

def xml = new groovy.xml.XmlSlurper().parseText(xmlStr)

// starting at the root element, get every row tag and then 
// every date tag within that row and then get the text contents 

def dates = xml.row.date*.text()

// lets parse every date string we found into a date object; the 
// collect {} method is similar to the js map method

dates = dates.collect { new SimpleDateFormat("yyyymmdd").parse(it) }

// now lets check that the scraped values are the same as a listed of 
// sorted values - we add the 'false' parameter to sort so that we do 
// not mutate the original list 

assert dates == dates.sort(false)

有关一些有用的信息,请查看groovy docs for working with XML

相关问题