我想阅读并打开.yml文件并使用Nokogiri创建XML?谁能告诉我怎么做?
这是Yaml格式:
getOrderDetails:
Id: '114'
Name: 'XYZ'
这是我需要的XML:
<product> <id>123</id> <name>xyz</name> </product>
这是ruby文件:
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
答案 0 :(得分:2)
如果你知道你想要的字段:
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>
如果要根据Yaml键的名称创建任意XML文件:
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>