您的位置:首页 > Web前端 > JavaScript

Parse xml/json[xpath/jpath]

2016-06-01 16:45 661 查看
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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: