I want to try an retrieve the name of a hotel (in this example the hotel is called 'Test Hotel'), but I am unsure how to do it because I believe to get a #node it's using # but how do I retrieve a text?
Below is the xml:
<xxx xmlns:soap="xxx" xmlns:xsi="xxx" xmlns:xsd="xxx">
<xxx>
<xxxxmlns="xxx">
<AvailabilityRS Url="xxx" IntCode="xxx">
<Results>
<HotelResult Code="xxx"DestinationZone="xxx">
<HotelInfo>
<Name>Test Hotel</Name>
Below is the script:
def response = testRunner.testCase.getTestStepByName("xxx").getProperty("Response").getValue()
def parsedxml = new XmlSlurper().parseText(response)
def hotelName = parsedxml.'soap:Body'.HotelAvailResponse[0].xxx[0].Results[0].xxxx[0].xxx[0].Name[0].toString()
Instead of using toString(), you should be able to just use text()
def hotelName = parsedxml.Body
.HotelAvailResponse
.AvailabilityRS
.Results
.HotelResult
.HotelInfo
.Name.text()
Related
I tried xml_marshaller as follows:
from xml_marshaller import xml_marshaller
class Person:
firstName = "John"
lastName = "Doe"
person1 = Person()
strXmlPerson = xml_marshaller.dumps(person1);
print(strXmlPerson)
The output from above is:
b'<marshal><object id="i2" module="__main__" class="Person"><tuple/><dictionary id="i3"><string>firstName</string><string>John</string><string>lastName</string><string>Doe</string></dictionary></object></marshal>'
which when formatted looks like this, which in my opinion is the ugliest XML possible:
b'<marshal>
<object id="i2" module="__main__" class="Person">
<tuple/>
<dictionary id="i3">
<string>firstName</string>
<string>John</string>
<string>lastName</string>
<string>Doe</string>
</dictionary>
</object>
</marshal>'
What is the b and quotes doing there? Means "binary" maybe? Is that really part of the data, or just a side effect of printing it to the console?
Is there any Python 3 library that will create something more closer to "human" like this:
<Person>
<firstname>John</firstname>
<lastname>Doe<lastname>
</Person>
I'm looking for something close to what .NET creates (see http://mylifeismymessage.net/xml-serializerdeserializer/.
Please don't tell me try JSON or YAML, that's not the question. I might want to run the file through XSLT for example.
Update 2 days later:
I like the Peter Hoffman answer here:
How can I convert XML into a Python object?
person1 = Person("John", "Doe")
#strXmlPerson = xml_marshaller.dumps(person1);
person = objectify.Element("Person")
strXmlPerson = lxml.etree.tostring(person1, pretty_print=True)
print(strXmlPerson)
gives error:
TypeError: Type 'Person' cannot be serialized.
In my scenario I might already have a class structure, and don't want to switch to they way they are doing it You can I serialize my "Person" class?
The reason the output is showing xml as a dictionary is most likely because the properties don't have a reference to the class. You should consider using self. and assigning values within a __init__ function.
class Person:
def __init__(self):
self.firstName = "John"
self.lastName = "Doe"
There are many ways to convert an object to XML. However try using the package dicttoxml. As the name suggest you'll need to convert object to a dictionary, which can be done using vars().
The full solution:
from dicttoxml import dicttoxml
class Person:
def __init__(self):
self.firstName = "John"
self.lastName = "Doe"
person = vars(Person()) # vars is pythonic way of converting to dictionary
xml = dicttoxml(person, attr_type=False, custom_root='Person') # set root node to Person
print(xml)
Output:
b'<?xml version="1.0" encoding="UTF-8" ?><Person><firstName>John</firstName><lastName>Doe</lastName></Person>'
If you want to format the XML nicely, then you can use the built in xml.dom.minidom.parseString library.
from dicttoxml import dicttoxml
from xml.dom.minidom import parseString
class Person:
def __init__(self):
self.firstName = "John"
self.lastName = "Doe"
person = vars(Person()) # vars is pythonic way of converting to dictionary
xml = dicttoxml(person, attr_type=False, custom_root='Person') # set root node to Person
print(xml)
dom = parseString(xml)
print(dom.toprettyxml())
Output:
<?xml version="1.0" ?>
<Person>
<firstName>John</firstName>
<lastName>Doe</lastName>
</Person>
Do check out the documentation https://pypi.org/project/dicttoxml/ as you can pass additional arguments to alter the output.
def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
log.info RawRecordsDateRangeResponse
My response is:
{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}
Here I want to get the value from the json response key as date.
Your response represents JSON document and it stores it in variable of type String. You can parse it using groovy.json.JsonSlurper class. Consider following example:
import groovy.json.JsonSlurper
def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
def json = new JsonSlurper().parseText(RawRecordsDateRangeResponse)
def url = json.'2018-09-03'
println url
Output:
https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json
If it's just the key of the JSON message you need rather than the value, you could use something like:
import groovy.json.JsonSlurper
def rawRecordsDateRangeResponse = '''{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}'''
def json = new JsonSlurper().parseText(rawRecordsDateRangeResponse)
def date = json.collect({it.key})
print date
This produces [2018-09-03].
I got a string from a server response:
responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"
then I do:
responseString[1..-2].tokenize(',')
got:
[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]
get(3) got:
""userid":"user_1""
what I need is the user_1, is there anyway I can actually get it? I have been stuck here, other json methods get similar result, how to remove the outside ""?
Thanks.
If you pull out the proper JSON from responseStr, then you can use JsonSlurper, as shown below:
def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'
def matcher = (s =~ /responseString:"(.*)"/)
assert matcher.matches()
def responseStr = matcher[0][1]
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(responseStr)
assert "user_1" == json.userid
This code can help you get you to the userid.
def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
def match = (str=~ /"userid":"(.*?)"/)
log.info match[0][1]
this pattern can help you getting any of the values you want from the string. Try replacing userid with age, you will get that
def match = (str=~ /"age":"(.*?)"/)
#Michael code is also correct. Its just that you have clarified that you want the user Name to be specific
I am trying to automate using groovy script. Here is my script. I am not able to mention namspace.
<ns2:contactPref xmlns="namespace 1" xmlns:ns2="name space 2">
<ns2:Information>
<value>Pass</value>
</ns2:Information>
<ns2:contactPreference>
<ns2:contactPointRel>
<contactPoint xs:type="Tele" xmlns:xs="namespace 3">
<cat>mob</cat>
<med>Int</med>
</contactPoint>
</ns2:contactPointRel>
</ns2:contactPreference>
</ns2:contactPref>
Now I want to fetch attribute at contactPoint tag
for this I have tried like this
groovyUtils=new com.eviware.soapui.support.Groovyutills(context)
def xPath=XPathFactory.newInstance().newXPath()
def type=context.expand('${GetResponse#Response#//*:contactPoint/#xs:type}')
log.info type
tried this
def type=context.expand('${GetResponse#Response#//*:contactPoint/#type}')
and I also tried this
def resp=groovyUtils.getXmlHolder("GetResponse#Response")
def type1=(String)xPath.evaluate('//:contactpoint/#xs:type',resp,xPathConstants.STRING)
but no help. please some one tell me how to do this??
try using this it should work
#{namespace 3}type
if you see xs:type="Tele" xmlns:xs="namespace 3" in contactPoint then xs which has value namespace 3 and {type} is Tele
Edited - You could use something like this - with xmlString as XML
def xml = new XmlSlurper().parseText(xmlString)
println
xml.contactPreference.contactPointRel.contactPoint."#{namespace
3}type"
Hi In Groovy I need to remove part of string
the string.
<Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>
should look like " Updated User id:nish.test11
how can i do that?
As the content looks like an XML,
def xml = """
<Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>
"""
it's better to use XmlSlurper than parsing/extracting strings by hand
def result = new XmlSlurper().parseText(xml)
println result.toString()
this gives the desired result (the content of the Result)
If I run the code:
""" <Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>""".replaceAll( /<\/?[^<>]>/, '' ).replaceAll( /[\n\s]+/, ' ' )
it gives me
Updated User id:nish.test11
as output