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
相关文章推荐
- thinkjs使用Nunjucks模板以及简单的使用方法
- bzoj 4477: [Jsoi2015]字符串树
- 创建自定义JSR303的验证约束
- JSON风格指南
- Extjs5....布局,分页栏不不显示在最底端解决方法!
- layer弹出层关闭后刷新父页面
- javascript 之prototype
- XML、JSON及其解析
- 解析JSON数据后的两种显示方式
- js跳转页面的几种方法
- 【js框架】随笔
- ie下不打开控制台js无法执行
- JSON入门与实战 —— JavaScript、Java与JSON互转
- javascript百度地图添加一个普通标注点(2014-3-8 记)
- extjs
- Javascript原型
- Microsoft JScript提示‘DIRECT’未定义(2014-08-26记)
- javascript实现网页跳转的方法
- JS对象高级属性:数据属性与访问器属性
- Javascript对象创建