How to create XML from Yaml file using Nokogiri?

三世轮回 提交于 2019-12-10 12:24:51

问题


I want to read and open an .yml file and create an XML using Nokogiri ? Can anybody tell me how to do it ?

This is the Yaml format:

getOrderDetails: 
  Id: '114'
  Name: 'XYZ' 

This is the XML I need:

<product> <id>123</id> <name>xyz</name> </product>

And this is the ruby file:

require 'nokogiri'
require 'rubygems'
require 'spec/spec_helper'
require 'yaml'

@doc = YAML.load(File.open(File.expand_path('/Workspace/XML_Parsing/getDetails_api.yml'‌​)))
@doc = File.open('/Workspace/XML_Parsing/getDetails_api.yml')
builder = Nokogiri::XML::Builder.new do |xml|
  xml.doc {
    @doc.each do |o|
      o.doc.child {
        puts "eval(#{doc(:getDetails(['Id']))})"
        puts "#{doc['NameCode']}"
        #o.OrderNo
        #o.EnterpriseCode
      }
    end
  }
end

puts builder.to_xml

回答1:


If you know the fields you want specifically:

require 'yaml'
require 'nokogiri'

yaml = "getOrderDetails:
  Id: '114'
  Name: 'XYZ'"
doc = YAML.load yaml

output = Nokogiri::XML::Builder.new do |xml|
  xml.product{
    xml.id   doc["getOrderDetails"]["Id"]
    xml.name doc["getOrderDetails"]["Name"]
  }
end
puts output.to_xml
#=> <?xml version="1.0"?>
#=> <product>
#=>   <id>114</id>
#=>   <name>XYZ</name>
#=> </product>

If you want to create an arbitrary XML file based on the names of Yaml keys:

output = Nokogiri::XML::Builder.new do |xml|
  xml.product{
    doc["getOrderDetails"].each do |name,value|
      xml.send(name.downcase,value)
    end
  }
end
puts output.to_xml
#=> <?xml version="1.0"?>
#=> <product>
#=>   <id>114</id>
#=>   <name>XYZ</name>
#=> </product>


来源:https://stackoverflow.com/questions/7966180/how-to-create-xml-from-yaml-file-using-nokogiri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!