我需要将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
方法添加这些属性?
请建议是否有其他方法可以解决我的问题。
答案 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