Ruby + Nokogiri:如何使用attribute = value创建XML节点?

时间:2014-01-17 21:03:50

标签: ruby xml nokogiri

我必须使用XML向API发出请求:

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

我正在尝试使用Nokogiri来实现这一目标,但我不知道如何添加USERID="xxxx.."部分。这就是我所拥有的(不完整):

def xml_for_initial_request
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.CityStateLookupRequest.USERIDhowdoIsetthevalue?? {
      xml.Zip {
        xml.Zip5 '90210'
      }
    }
  end
end

1 个答案:

答案 0 :(得分:10)

我会这样做:

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>