Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby + Nokogiri: How to create XML node with attribute=value?

Tags:

xml

ruby

nokogiri

I have to make a request to an API with XML:

http://production.shippingapis.com/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxxxxxxx"> <ZipCode ID= "0"> <Zip5>90210</Zip5> </ZipCode> </CityStateLookupRequest>

I'm trying to use Nokogiri to achieve this, but I don't know how to add the USERID="xxxx.." part. This is what I have (incomplete):

def xml_for_initial_request
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.CityStateLookupRequest.USERIDhowdoIsetthevalue?? {
      xml.Zip {
        xml.Zip5 '90210'
      }
    }
  end
end
like image 519
bigpotato Avatar asked Jan 11 '23 10:01

bigpotato


1 Answers

I would do as below :

require 'nokogiri'

builder = Nokogiri::XML::Builder.new do |xml|
    xml.CityStateLookupRequest('userid' => 'xxxxxx' ) {
      xml.zip("id" => '10'){
        xml.Zip5 '90210'
      }
    }
end

puts builder.to_xml
# >> <?xml version="1.0"?>
# >> <CityStateLookupRequest userid="xxxxxx">
# >>   <zip id="10">
# >>     <Zip5>90210</Zip5>
# >>   </zip>
# >> </CityStateLookupRequest>
like image 191
Arup Rakshit Avatar answered Jan 18 '23 21:01

Arup Rakshit