提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
目录
ruby脚本可以用来完成自动化工作,需要学习一下
前言
提示:这里可以添加本文要记录的大概内容:ruby学习汇总
例如:ruby生成xml;
提示:以下是本篇文章正文内容,下面案例可供参考
一、基本语法
示例:
def newAB
file = File.new("test.xml","w+")
doc = REXML::Document.new
element = doc.add_element('a','A')
element.add_element('b','B')
doc.write
file.puts doc.write
end
def readXml
xmlfile = File.new("movie.xml")
xmldoc = Document.new(xmlfile)
# 获取 root 元素
root = xmldoc.root
puts "Root element : " + root.attributes["shelf"]
# 以下将输出电影标题
xmldoc.elements.each("collection/movie") {
|e| puts "Movie Title : " + e.attributes["title"]
}
# 以下将输出所有电影类型
xmldoc.elements.each("collection/movie/type") {
|e| puts "Movie Type : " + e.text }
# 以下将输出所有电影描述
xmldoc.elements.each("collection/movie/description") {
|e| puts "Movie Description : " + e.text
}
end
二、实际使用
1.生成xml
生成xml,有三级节点,通过批量操作list,循环生成节点内容
#!/usr/bin/ruby -w
require 'rexml/document'
include REXML
bdSoft = ['bdsoft1','bdsoft2']
soft = ['soft1','soft2']
offline_pkgs = ['pkg1','pkg2']
download = false
upload = true
file = File.new("test.xml","w+")
doc = REXML::Document.new "<root/>"
root_node = doc.root
el = root_node.add_element "a1"
el2 = el.add_element "a2-0", {"id"=>"10"}
# el1 = Element.new "myelement"
el2.text = "Hello world!"
# does the same, but also sets attribute "id" of el2 to "10"
el3 = REXML::Element.new "a2-1"
el3.attributes["name"] = "name"
el.elements << el3
bdSoft.each do |bd|
copy_element = REXML::Element.new "copy"
source_element = copy_element.add_element "source"
des_element = copy_element.add_element "des"
if download
source_element.text = bd
des_element.text = 'BdSoft'
elsif upload
source_element.text = 'BdSoft'
des_element.text = bd
end
el.elements << copy_element
end
soft.each do |soft|
copy_element = REXML::Element.new "copy"
source_element = copy_element.add_element "source"
des_element = copy_element.add_element "des"
if download
source_element.text = soft
des_element.text = 'Soft'
elsif upload
source_element.text = 'Soft'
des_element.text = soft
end
el.elements << copy_element
end
offline_pkgs.each do |pkg|
copy_element = REXML::Element.new "copy"
source_element = copy_element.add_element "source"
des_element = copy_element.add_element "des"
if download
source_element.text = pkg
des_element.text = 'offline_pkgs'
elsif upload
source_element.text = 'offline_pkgs'
des_element.text = pkg
end
el.elements << copy_element
end
file.puts doc.write
puts doc.to_s
2.TODO
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容