I have an XML file that I am trying to parse through with Groovy.
<?xml version = '1.0' encoding = 'UTF-8'?>
<ServerList>
<Server>server1.me.com</Server>
<CleanUpTest>TESTING</CleanUpTest>
<Server>server2.me.com</Server>
</ServerList>
This code works and gives me the output Result: [server1.me.com]:
def serverList = new XmlSlurper().parse("E:\\Program Files(x86)\\Jenkins\\jobs\\first_servers.xml")
def output = []
serverList.Server.find { it == 'server1.me.com' }.each{
output.add(it)
}
return output
But when I try to get the value in CleanUpTest it is not working.
def serverList = new XmlSlurper().parse("E:\\Program Files(x86)\\Jenkins\\jobs\\first_servers.xml")
def output = []
serverList.Server.find { it == 'server1.me.com' }.CleanUpTest.each{
output.add(it)
}
return output
What do I have wrong? I am expecting Result: [TESTING]
Related
I need to take my output from the for loop below and add it to a single array. The list object can either be ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"] or ["envName-inactive-2", "", "", "envName-active-2"]
My code:
if (appendVersion) {
for (elements in list) {
test = (elements + "-" + branch)
println(test)
}
} else {
println(list)
}
output:
envName-inactive-1-v2
active-1-v2
inactive-1-v2
envName-active-1-v2
and
envName-inactive-2-v2
-v2
-v2
envName-active-2-v2
desired output:
["envName-inactive-1-v2", "active-1-v2", "inactive-1-v2", "envName-active-1-v2"]
and
["envName-inactive-2-v2", "", "", "envName-active-2-v2"]
You desired format seems to be json. In Jenkins you have option to use writeJSON to convert list to json format.
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = writeJSON returnText: true, json: versionedList
println json
the same in plain groovy:
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = new groovy.json.JsonBuilder(versionedList).toString()
println json
result:
["envName-inactive-1-v2","active-1-v2","inactive-1-v2","envName-active-1-v2"]
I have a question on how to assert the element_count equals to the number of objects from response.
The link to the API is https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=*******
I tried using the below code but did not have any luck trying to count the objects from the JSON response using grrovy script.
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def response = new JsonSlurper().parseText(ResponseMessage)
def elementCount = response.element_count
def idCount = response.count { it.equals('neo_reference_id') }
I was trying to count the number of neo_reference_id which should equal element_count. Any help would be great.
def url = new URL('https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=***')
def response = new groovy.json.JsonSlurper().parse( url )
def neo_references = response.near_earth_objects.collectMany{date,objects-> objects.collect{it.neo_reference_id} }
println neo_references
println neo_references.size()
assert response.element_count == neo_references.size()
I want to parse a xml file during build time in build.gradle file and want to modify some values of xml, i follow this SO question and answer Load, modify, and write an XML document in Groovy but not able to get any change in my xml file. can anyone help me out. Thanks
code in build.gradle :
def overrideLocalyticsValues(String token) {
def xmlFile = "/path_to_file_saved_in_values/file.xml"
def locXml = new XmlParser().parse(xmlFile)
locXml.resources[0].each {
it.#ll_app_key = "ll_app_key"
it.value = "123456"
}
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile)))
nodePrinter.preserveWhitespace = true
nodePrinter.print(locXml)
}
xml file :
<resources>
<string name="ll_app_key" translatable="false">MY_APP_KEY</string>
<string name="ll_gcm_sender_id" translatable="false">MY_GCM_SENDER_ID</string>
</resources>
In your code : Is it right ...? Where is node name and attribute ..?
locXml.resources[0].each { // Wrongly entered without node name
it.#ll_app_key = "ll_app_key" // Attribute name #name
it.value = "123456" // you can't change or load values here
}
You tried to read and write a same file. Try this code which replaces the exact node of the xml file. XmlSlurper provides this facility.
Updated :
import groovy.util.XmlSlurper
import groovy.xml.XmlUtil
def xmlFile = "test.xml"
def locXml = new XmlSlurper().parse(xmlFile)
locXml.'**'.findAll{ if (it.name() == 'string' && it.#name == "ll_app_key") it.replaceBody 12345 }
new File (xmlFile).text = XmlUtil.serialize(locXml)
Groovy has a better method for this than basic replacement like you're trying to do - the SimpleTemplateEngine
static void main(String[] args) {
def templateEngine = new SimpleTemplateEngine()
def template = '<someXml>${someValue}</someXml>'
def templateArgs = [someValue: "Hello world!"]
println templateEngine.createTemplate(template).make(templateArgs).toString()
}
Output:
<someXml>Hello world!</someXml>
I want to perform an assertion within SOAP UI to check if the 'BookingCode' is displayed but I am not sure how to do it. I am using .size() but it keeps failing whether there is or isn't any booking code:
Below is an xml example but I xxx out the information:
<soap:xxx">
<soap:Body>
<getBookingsResponse xmlns="http://xxx/">
<Bookings>
<Booking Id="xxx" BookingCode="xxx" >
Below is the script assertion itself:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def serviceResponse = context.expand( '${getBookings#Response}' )
def xml = new XmlSlurper().parseText( serviceResponse )
def BookingRef = xml.'soap:Body'.getBookingsResponse[0].Bookings[0].Booking.#BookingCode
assert BookingRef.size() != 0
Thank you
Here you go, comments in-line:
Script Assertion
//Pass the xml string to parseText method
def pxml = new XmlSlurper().parseText(context.response)
//Get the BookingCode attributes
def codes = pxml.'**'.findAll{ it.name() == 'Booking' }*.#BookingCode*.text()
log.info codes
assert codes.size !=0
there is a simple xml, for example:
def rootNode = new XmlSlurper().parseText(
'<root>
<one a1="uno!"/>
<two>Some text!</two>
</root>' )
how can i insert a node
<three type='c'>2334</three>
into root?
i have use this way to insert
rootNode.appendNode{three(type:'c') 2334}
rootNode = new XmlSlurper().parseText(rootNode)
but it return exception.
Below script should give you desired result:
change from yours: three (type:'c', 2334)
import groovy.xml.*
def rootNode = new XmlSlurper().parseText('<root><one a1="uno!"/><two>Some text!</two></root>' )
rootNode.appendNode {
three (type:'c', 2334)
}
def newRootNode = new StreamingMarkupBuilder().bind {mkp.yield rootNode}.toString()
println newRootNode
Output:
<root><one a1='uno!'></one><two>Some text!</two><three type='c'>2334</three></root>