从XML转换到rest-client以获取POST请求

时间:2014-11-11 21:08:28

标签: ruby xml rest-client

是我必须通过POST发出的XML请求才能收到回复:

<BackgroundCheck userId="username" password="password">
  <BackgroundSearchPackage action="submit" type="demo product">
    <ReferenceId>some_id_value</ReferenceId>
    <PersonalData>
      <PersonName>
        <GivenName>John</GivenName>  
        <MiddleName>Q</MiddleName>
        <FamilyName>Test</FamilyName>
      </PersonName>
      <Aliases>
        <PersonName>
          <GivenName>Jack</GivenName>
          <MiddleName>Quigley</MiddleName>
          <FamilyName>Example</FamilyName>
        </PersonName>
      </Aliases>
      <DemographicDetail>
        <GovernmentId issuingAuthority="SSN">123456789</GovernmentId>
        <DateOfBirth>1973-12-25</DateOfBirth>
      </DemographicDetail>
      <PostalAddress>
        <PostalCode>83201</PostalCode>
        <Region>UT</Region>
        <Municipality>Salt Lake City</Municipality>
        <DeliveryAddress>
          <AddressLine>1234</AddressLine>
          <StreetName>Main Street</StreetName>
        </DeliveryAddress>
      </PostalAddress>
      <EmailAddress>john@test.com</EmailAddress>
      <Telephone>801-789-4229</Telephone>
    </PersonalData>
  </BackgroundCheck>
</BackgroundSearchPackage>

使用rest-client github page上的示例我使用rest-client提出了以下翻译:

response = RestClient.post( 'url',
  {
    :BackgroundCheck => {
      :userID => 'username',
      :password => 'password',
    }, 
    :BackgroundSearchPackage => {
      :action => 'submit',
      :type => 'demo'
    }, 
    :ReferenceID => 'some_id_value', 
    :PersonalData => {
      :PersonalName => {
        :GivenName => 'John',
        :MiddleName => 'Q',
        :FamilyName => 'Test'
      }, 
       :Aliases => {
        :GivenName => 'Jack',
        :MiddleName => 'Quigly',
        :FamilyName => 'Example'
      }
    }, 
    :DemographicDetail => {
      :GovernmentId => {
        :issuingAuthority => "SSN"
      },  ## where do I enter the SSN?
      :DateOfBirth => '1972-12-25'
    }, 
    :PostalAddress => {
      :PostalCode => '83201',
      :Region => 'UT',
      :Municipality => 'Salt Lake City',
      :DeliveryAddress => {
        :AddressLine => '1234',
        :StreetName => 'Main Street'
      }
    }, 
    :EmailAddress => 'john@test.com', 
    :Telephone => '801-789-4229'
  })

这是我第一次使用XML和rest-client gem。

我的问题是我在POST请求中正确翻译了XML吗?

更具体地说,我如何处理GovernmentID并引用SSN条目?

1 个答案:

答案 0 :(得分:1)

首先,您提供的XML无效!您的根元素以BackgroundCheck开头,以BackgroundSearchPackage结尾:

<BackgroundCheck userId="username" password="password">
  <BackgroundSearchPackage action="submit" type="demo product">
  </BackgroundCheck>
</BackgroundSearchPackage>

此外,您从XML到Ruby哈希的转换/转换是不正确的。如果BackgroundCheck是你的根元素而BackgroundSearchPackage是它的子元素,那么你的Ruby哈希应该是这样的(rest-client接受字符串和符号表示法):

my_xml_hash = {
  "BackgroundCheck" => {
    "userId"=>"username",
    "password"=>"password",
    "BackgroundSearchPackage" => {
      "action"=>"submit",
      "type"=>"demo product",
      ...
      "PersonalData" => { ... },
      ...
    }
  }
}

您可以像这样访问Ruby哈希值:

# string syntax
my_xml_hash['BackgroundCheck']['BackgroundSearchPackage']['PersonalData']['DemographicDetail']['GovernmentId']
 => "123456789"

# symbol syntax
other_xml_hash[:BackgroundCheck][:BackgroundSearchPackage][:PersonalData][:DemographicDetail]['GovernmentId']
 => "123456789"

<小时/> <小时/>

如果我理解正确,您希望通过POST请求发送XML。但是如果你使用哈希语法,你将无法实现你想要的结果,因为rest-client会将你的数据作为参数而不是XML数据发布!

如果您只需要调整GovernmentIDissuingAuthority,我会按以下方式进行调整。

require 'rest_client'

# the customized 'GovernmentID'
government_id = '123'

# the customized 'issuingAuthority'
issuing_authority = 'FOO'

xml_template =<<END_OF_XML
  <BackgroundCheck userId="username" password="password">
    <BackgroundSearchPackage action="submit" type="demo product">
      <ReferenceId>some_id_value</ReferenceId>
      <PersonalData>
        <PersonName>
          <GivenName>John</GivenName>  
          <MiddleName>Q</MiddleName>
          <FamilyName>Test</FamilyName>
        </PersonName>
        <Aliases>
          <PersonName>
            <GivenName>Jack</GivenName>
            <MiddleName>Quigley</MiddleName>
            <FamilyName>Example</FamilyName>
          </PersonName>
        </Aliases>
        <DemographicDetail>
          <GovernmentId issuingAuthority="#{issuing_authority}">#{government_id}</GovernmentId>
          <DateOfBirth>1973-12-25</DateOfBirth>
        </DemographicDetail>
        <PostalAddress>
          <PostalCode>83201</PostalCode>
          <Region>UT</Region>
          <Municipality>Salt Lake City</Municipality>
          <DeliveryAddress>
            <AddressLine>1234</AddressLine>
            <StreetName>Main Street</StreetName>
          </DeliveryAddress>
        </PostalAddress>
        <EmailAddress>john@test.com</EmailAddress>
        <Telephone>801-789-4229</Telephone>
      </PersonalData>
    </BackgroundSearchPackage>
  </BackgroundCheck>
END_OF_XML

# Go to http://requestb.in/ , click on "Create a RequestBin", copy the "Bin URL" and use it for your tests ;-)
response = RestClient.post('http://your.target.tld/your/webservice', xml_template, { content_type: :xml })

puts "Response: #{response.inspect}"

<小时/> <小时/>

REXML示例:

require 'rest_client'
require 'rexml/document'

xml_string =<<END_OF_XML
  <BackgroundCheck userId="username" password="password">
    <BackgroundSearchPackage action="submit" type="demo product">
      <ReferenceId>some_id_value</ReferenceId>
      <PersonalData>
        <PersonName>
          <GivenName>John</GivenName>  
          <MiddleName>Q</MiddleName>
          <FamilyName>Test</FamilyName>
        </PersonName>
        <Aliases>
          <PersonName>
            <GivenName>Jack</GivenName>
            <MiddleName>Quigley</MiddleName>
            <FamilyName>Example</FamilyName>
          </PersonName>
        </Aliases>
        <DemographicDetail>
          <GovernmentId issuingAuthority="SSN">123456789</GovernmentId>
          <DateOfBirth>1973-12-25</DateOfBirth>
        </DemographicDetail>
        <PostalAddress>
          <PostalCode>83201</PostalCode>
          <Region>UT</Region>
          <Municipality>Salt Lake City</Municipality>
          <DeliveryAddress>
            <AddressLine>1234</AddressLine>
            <StreetName>Main Street</StreetName>
          </DeliveryAddress>
        </PostalAddress>
        <EmailAddress>john@test.com</EmailAddress>
        <Telephone>801-789-4229</Telephone>
      </PersonalData>
    </BackgroundSearchPackage>
  </BackgroundCheck>
END_OF_XML

# Build XML document from string
doc = REXML::Document.new(xml_string)
government_element = REXML::XPath.first(doc, "//GovernmentId")

# Read values:
puts government_element.text
puts government_element.attributes['issuingAuthority']
# OR directly via XPath
puts REXML::XPath.first(doc, "//GovernmentId").text
puts REXML::XPath.first(doc, "//GovernmentId/@issuingAuthority").value

# Write values: 
government_element.text = 'my new text value'
government_element.attributes['issuingAuthority'] = 'my new attribute value'

# Go to http://requestb.in/ , click on "Create a RequestBin", copy the "Bin URL" and use it for your tests ;-)
response = RestClient.post('http://your.target.tld/your/webservice', doc.to_s, { content_type: :xml })

puts "Response: #{response.inspect}"

<小时/> <小时/>

如果您需要编写复杂的XML树,我建议您查看以下宝石:

或者使用像ERB这样的模板引擎来简化它。