{ "Username" => '123456', -6ren">
gpt4 book ai didi

ruby-on-rails - ruby to_xml 设置根属性

转载 作者:太空宇宙 更新时间:2023-11-03 17:46:08 25 4
gpt4 key购买 nike

我需要将 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 方法添加这些属性?

如果有任何其他方法可以解决我的问题,请提出建议。

最佳答案

您需要使用自定义生成器。这是 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 应该在 builder 之前定义

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

关于ruby-on-rails - ruby to_xml 设置根属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37134172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com