views:

44

answers:

1

Alright, so the ultimate goal here is to parse the data inside of an xml response. The response comes in the format of a ruby string. The problem is that I'm getting an error when creating the xml file from that string (I know for a fact that response.body.to_s is a valid string of xml:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <CardTxn>
    <authcode>123</authcode>
    <card_scheme>Mastercard</card_scheme>
    <country>United Kingdom</country>
  </CardTxn>
  <datacash_reference>XXXX</datacash_reference>
  <merchantreference>XX0001</merchantreference>
  <mode>TEST</mode>
  <reason>ACCEPTED</reason>
  <status>1</status>
  <time>1286477267</time>
</Response>

Inside the ruby method I try to generate an xml file:

doc = Nokogiri::XML(response.body.to_s)

the output of doc.to_s after the above code executes is:

<?xml version="1.0"?>

Any ideas why the file is not getting generated correctly?

A: 

This works for me on 1.9.2. Notice it's Nokogiri::XML.parse().

require 'nokogiri'
asdf = %q{<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <CardTxn>
    <authcode>123</authcode>
    <card_scheme>Mastercard</card_scheme>
    <country>United Kingdom</country>
  </CardTxn>
  <datacash_reference>XXXX</datacash_reference>
  <merchantreference>XX0001</merchantreference>
  <mode>TEST</mode>
  <reason>ACCEPTED</reason>
  <status>1</status>
  <time>1286477267</time>
</Response>
}

doc = Nokogiri::XML.parse(asdf)
print doc.to_s

This parses the XML into a Nokogiri XML document, but doesn't create a file. doc.to_s only shows you what it would be like if you printed it.

To create a file replace "print doc.to_s" with

File.open('xml.out', 'w') do |fo|
  fo.print doc.to_s
end
Greg