如何使用 Nokogiri 从 Yaml 文件创建 XML? [英] How to create XML from Yaml file using Nokogiri?

查看:59
本文介绍了如何使用 Nokogiri 从 Yaml 文件创建 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取并打开一个 .yml 文件并使用 Nokogiri 创建一个 XML?谁能告诉我怎么做?

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

这是 Yaml 格式:

This is the Yaml format:

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

这是我需要的 XML:

This is the XML I need:

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

这是红宝石文件:

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

推荐答案

如果您知道具体需要的字段:

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>

如果要根据 Yaml 键的名称创建任意 XML 文件:

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>

这篇关于如何使用 Nokogiri 从 Yaml 文件创建 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆