使用Nokogiri生成包含嵌套标记和命名空间的XML

时间 2019-02-22
阅读 29
点赞 0
收藏 0
连接jl118

使用gem 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:transactionid标记中,因此输出不符合要求。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>

谢谢。

建议答案

您只需要一个生成器:

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>
👍 0