如何从Savon回复中读取价值?

时间:2012-06-27 10:32:13

标签: ruby nokogiri watir savon

我想从以下回复中读取customer.customer_info_id的值。我的回复还包括名称空间:

<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>

我尝试了以下内容:

# 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}"

返回空值。

3 个答案:

答案 0 :(得分:2)

我认为没有必要解析XML响应。萨翁为你做到了。 您没有提供通话代码,因此我认为它将是 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]

我经常使用pp response.to_hash来了解返回的内容。

答案 1 :(得分:0)

我与萨文的结果好坏参半。最终我正在处理的WSDL返回一个需要解析的StringWithAttributes类,但直到它应该像普通哈希一样,这意味着你应该能够做类似的事情:

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]

如果您仍然获得空值,请在每个级别尝试pp response[:soap_response].class.keys,以确保您仍在处理哈希值。如果它成为奇怪的StringwithAttributes类,你将不得不解析它。这似乎发生在下降到许多级别后。在这种情况下,你可以这样做:

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

parsed = Nori.parse(needs_parsing)

然后你应该回到一个可导航的哈希,你可以用.class查看。

答案 2 :(得分:0)

以下使用Nokogiri的代码可以读取特定的xml元素值:

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

element=doc.at('element_name') #fetch the value of element needed.
相关问题