木吟

导航

Parse xml/json[xpath/jpath]

import groovy.util.XmlSlurper
import groovy.util.XmlParser
import com.eviware.soapui.support.GroovyUtils
import com.jayway.jsonpath.*

def xmlStr = '<root><one a1="uno!"/><one a1="aaa"/><two>Some text!</two></root>'
def rootNode

// use XmlSlurper to parse xml, return GPathResult instances
rootNode = new XmlSlurper().parseText(xmlStr)
assert rootNode.name() == "root"
assert rootNode.one[0].@a1 == "uno!"
assert rootNode.two == "Some text!"

// use XmlParser to parse xml, return Node objects
rootNode = new XmlParser().parseText(xmlStr)
assert rootNode.name() == "root"
assert rootNode.one[0].@a1 == "uno!"
assert rootNode.one[0]["@a1"] == "uno!"
assert rootNode.one[0].attribute("a1") == "uno!"
assert rootNode.two.text() == "Some text!"
rootNode.children().each { assert it.name() in ['one','two'] }

/*
 * When to use XmlSlurper or XmlParser?
 * If you want to transform an existing document to another then XmlSlurper will be the choice.
 * If you want to update and read at the same time then XmlParser is the choice.
 * If you just have to read a few nodes XmlSlurper should be your choice, since it will not have to create a complete structure in memory".
 */

// use GroovyUtils.getXmlHolder().getDomNodes() to parse xml with xpath
def groovyUtils = new GroovyUtils(context)
def xmlHolder = groovyUtils.getXmlHolder(xmlStr)
def nodesArray = xmlHolder.getDomNodes("//one")
def oneNodeAttrValue = nodesArray[1].getAttribute("a1")
log.info oneNodeAttrValue

// use JsonPath.read() to parse json with jpath
def jsonStr = '{"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99}],"bicycle":{"color":"red","price":19.95}},"expensive":10}'
def authors = JsonPath.read(jsonStr, '$.store.book[*].author')
log.info authors

 

posted on 2016-06-01 16:45  木吟  阅读(417)  评论(0编辑  收藏  举报