1. 程式人生 > >Ruby之————XML建立與解析

Ruby之————XML建立與解析

#生成XML,需要建立一個REXML::Document物件例項 
require "rexml/document" 
file = File.new("test.xml","w+")    #新建XML檔案, 將以下內容寫入 。
doc = REXML::Document.new       #建立XML內容 
#為REXML文件新增一個節點 
element = doc.add_element ('book', {'name'=>'Programming Ruby', 'author'=>'Joe Chu'})
chapter1 = element.add_element( 'chapter',{'title'=>'chapter 1'})
chapter2 = element.add_element

 ('chapter', {'title'=>'chapter 2'})
#為節點新增包含內容
chapter1.add_text "Chapter 1 content"
chapter2.add_text "Chapter 2 content"

doc.write 
file.puts doc.write

#解析XML 
require "rexml/document" 
xml_doc = %{
<book name= 'Programming Ruby' author='Joe Chu'>
  <chapter title='chapter 1'>
    Chapter 1 content
  </chapter>
  <chapter title='chapter 2'>
    Chapter 2 content
  </chapter>
</book>

 
}
#建立REXML::文件例項, 並解析xml_doc文件, We can use the last file 'xml_doc', or last file test.xml 
#~ doc = REXML::Document.new(xml_doc) 
doc = REXML::Document.new(File.open("test.xml")) 
puts  doc.root.name #輸出跟節點名 
puts  doc.root.attributes['name'] #輸出根節點的name屬性值 
puts  doc.root.attributes['author'] #輸出根節點的author屬性值
 
chapter1 = doc.root.elements[1] #輸出節點中的子節點 
puts  chapter1.attributes['title']  #輸出第一個節點的title屬性值 
puts  chapter1.text #輸出第一個節點的包含文字