问题
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