使用Nokogiri进行XML生成,涉及嵌套标签和名称空间

时间:2019-02-21 17:54:52

标签: ruby-on-rails ruby xml nokogiri

使用宝石Nokogiri,我正在尝试生成XML:

<?xml version='1.0'?>
  <env:Envelope xmln:env = "http://abc.ca">
    <env:Header> 
      <mm7:TransactionID xmlns:mm7="http://def.ca"> Some Text Here </mm7:TransactionID>
    </env:Header>
  </env:Envelope>

我的代码是:

env_ns = {
  "xmlns:env" => "http://abc.ca"
}

mm7_ns = {
  "xmlns:mm7" => "http://def.ca"
}

env_header = Nokogiri::XML::Builder.new do |xml|
  xml['mm7'].TransactionID(mm7_ns) do
    "Some Text Here"
  end
end

builder = Nokogiri::XML::Builder.new { |xml|
  xml['env'].Envelope(env_ns) do
    xml.Header do
      env_header
    end
  end
}

puts env_header.to_xml
puts "----------------------"

puts builder.to_xml

但是,由于值“ Some Text Here”不在mm7:TranactionID标记内,因此输出不是所期望的。 mm7标签没有放在标头标签内。另外,标头标签也不在信封标签内。

<?xml version="1.0"?>
  <mm7:TransactionID xmlns:mm7="http://def.ca"/>
-----------------------------------------------------------
<?xml version="1.0"?>
  <env:Envelope xmlns:env="http://abc.ca">
   <env:Header/>
  </env:Envelope>

谢谢。

1 个答案:

答案 0 :(得分:0)

您只需要1个构建器:

env_ns = {
  "xmlns:env" => "http://abc.ca"
}

mm7_ns = {
  "xmlns:mm7" => "http://def.ca"
}

builder = Nokogiri::XML::Builder.new do |xml|
  xml['env'].Envelope(env_ns) do
    xml.Header do
      xml['mm7'].TransactionID(mm7_ns, "Some Text Here")
    end
  end
end

puts builder.to_xml

# will render the following:
# <?xml version="1.0"?>
# <env:Envelope xmlns:env="http://abc.ca">
#   <env:Header>
#     <mm7:TransactionID xmlns:mm7="http://def.ca">Some Text Here</mm7:TransactionID>
#   </env:Header>
# </env:Envelope>