ruby to_xml设置root属性

时间:2016-05-10 09:17:41

标签: ruby-on-rails ruby xml data-conversion

我需要将ruby哈希转换为xml。这是哈希:

hash = {
      "AffiliateInfo" => {
      "Username" => '123456',
      "Password" => "Mypass",
      "TrackingCampaign" => "MyTrackingCampaign",
      "Env" => "production"
    }
  }

和我想要生成的xml:

<?xml version="1.0" encoding="UTF-8"?>
<InsuranceRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <AffiliateInfo>
  <Username>12696</Username>
  <Password>MyPassword</Password>
  <TrackingCampaign>MyTrackingCampaign</TrackingCampaign>
  <LeadSourceID>SourceID</LeadSourceID>
  <ProductionEnvironment>true</ProductionEnvironment>
  </AffiliateInfo>
</InsuranceRequest>

当我这样做时:

hash.to_xml(root: 'InsuranceRequest')

我得到以下xml输出

<?xml version="1.0" encoding="UTF-8"?>
<InsuranceRequest>
  <AffiliateInfo>
    <Username>123456</Username>
    <Password>Mypass</Password>
    <TrackingCampaign>MyTrackingCampaign</TrackingCampaign>
    <Env>production</Env>
  </AffiliateInfo>
</InsuranceRequest>

输出缺少根节点属性的属性:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"

我无法向根节点添加属性。有没有办法使用to_xml方法添加这些属性?

请建议是否有其他方法可以解决我的问题。

1 个答案:

答案 0 :(得分:4)

您需要使用自定义构建器。这是Nokogiri建设者的例子

require 'nokogiri'

hash = {"AffiliateInfo" => {
          "Username" => '123456',
          "Password" => "Mypass",
          "TrackingCampaign" => "MyTrackingCampaign",
          "Env" => "production"
         }
       }


builder = Nokogiri::XML::Builder.new do |xml|
  xml.InsuranceRequest('xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema') do
    xml.AffiliateInfo do
      hash['AffiliateInfo'].each do |k, v|
        xml.send(k, v)
      end
    end
  end
end

builder.to_xml

这将生成以下XML文档

<?xml version="1.0"?>
<InsuranceRequest
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <AffiliateInfo>
        <Username>123456</Username>
        <Password>Mypass</Password>
        <TrackingCampaign>MyTrackingCampaign</TrackingCampaign>
        <Env>production</Env>
    </AffiliateInfo>
</InsuranceRequest>

请注意hash应在构建器

之前定义

以下是Nokogiri文档http://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri/XML/Builder