Ruby之 XML建立與解析

2021-09-30 04:09:34 字數 1105 閱讀 5396

#生成xml,需要建立乙個rexml::document物件例項

require "rexml/document"

file = file.new("test.xml","w+")    #新建xml檔案, 將以下內容寫入 。

doc = rexml::document.new       #建立xml內容

#為rexml文件新增乙個節點

element = doc.add_element ('book', )

chapter1 = element.add_element( 'chapter',)

chapter2 = element.add_element ('chapter', )

#為節點新增包含內容

chapter1.add_text "chapter 1 content"

chapter2.add_text "chapter 2 content"

doc.write

file.puts doc.write

#解析xml

require "rexml/document"

xml_doc = %

#建立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 #輸出第乙個節點的包含文字

Ruby之 XML建立與解析

生成xml,需要建立乙個rexml document物件例項 require rexml document file file.new test.xml w 新建xml檔案,將以下內容寫入 doc rexml document.new 建立xml內容 為rexml文件新增乙個節點 element d...

ruby解析xml檔案

1.xml檔案如下 gar001 計算機組裝與維護教程 借閱時間 2008 03 14t17 23 28劉瑞新 機械工業出版社1中文 ctec gar002 計算機接 術 借閱時間 2008 03 14t17 27 16劉星等 機械工業出版社1中文 ctec gar003 數值分析與演算法 借閱時間...

Ruby解析XML簡單實現

animation.xml 動畫 黑貓警長 葫蘆娃大頭兒子小頭爸爸 舒克貝塔 貓和老鼠 海綿寶寶 變形金剛 大力水手 史努比的故事 獅子王 clannad 涼宮春日的憂鬱 fate zero 命運石之門 反叛的魯路修 eva潘朵拉之心 test.rb require rexml document i...