bigpotato
bigpotato

Reputation: 27497

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

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

Upvotes: 5

Views: 2802

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

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>

Upvotes: 10

Related Questions