Suriyakanth
Suriyakanth

Reputation: 267

Read value from a Savon response?

I want to read the value of customer.customer_info_id from the following response. My response also includes namespaces:

<Field name="customer.customer_id" value="5403699387967341892"/>
<Field name="**customer.customer_info_id**" value="5403699387967341892"/>
<Field name="customer.customer_since_code" value="1985">
    <Lookup language="EN" value="1985"/>
    <Lookup language="FR" value="1985"/>
</Field>

I tried the following:

# Savon code tried:        

doc = Nokogiri::XML(response.to_xml)
doc.remove_namespaces!
val = doc.xpath("//Field:name" => "Customer.entity_id").to_s
puts "val is: #{val}"

It returns null value.

Upvotes: 3

Views: 3825

Answers (3)

Suriyakanth
Suriyakanth

Reputation: 267

The below code using Nokogiri worked out to read a particular xml element value:

doc=Nokogiri.XML(File.open(File.dirname("your file name here"))

element=doc.at('element_name') #fetch the value of element needed.

Upvotes: 0

user1007711
user1007711

Reputation:

I have had mixed results with Savon. Eventually the WSDL I'm dealing with returns a StringWithAttributes class that requires parsing, but until that it should behave like a normal hash meaning you should be able to just do something like:

client = Savon::Client.new do
  wsdl.document = <your url>
end

response = client.request(:whatever_the_request_is_called) do
  soap.body = { <hash of your parameters> }
end

result = response[:soap_response][:soap_result][:customer][:customer_info_id]

If you're still getting null values, try a pp response[:soap_response].class or .keys on each level to make sure you're still working with a hash. If it becomes the weird StringwithAttributes class you'll have to parse it. This seems to happen after going down to many levels. In that case you can do something like this:

needs_parsing = response.to_hash[:soap_response][:soap_result]

parsed = Nori.parse(needs_parsing)

Then you should be back to a navigable hash, which you can check with .class.

Upvotes: 0

Steffen Roller
Steffen Roller

Reputation: 3494

I don't think it's necessary to parse the XML response. Savon does it for you. You didn't provide the code for the call so I assume it will be soap.

client = Savon::Client.new do
  wsdl.document = <your url>
end

response = client.request :wsdl, :soap do
  <your parameters go here>
end

# pp response.to_hash

result = response.to_hash[:soap_response][:soap_result][:customer][:customer_info_id]

I often use pp response.to_hash to get an idea what's returned.

Upvotes: 2

Related Questions