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

來源:互聯網
上載者:User

#產生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 #輸出第一個節點的包含文本

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.