现在的位置: 首页 > 综合 > 正文

Ruby之————XML创建与解析

2012年08月14日 ⁄ 综合 ⁄ 共 1092字 ⁄ 字号 评论关闭

#生成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 #输出第一个节点的包含文本

 

抱歉!评论已关闭.