使用Ruby对XML进行操作

上一篇 / 下一篇  2013-03-06 15:55:49 / 个人分类:测试

Ruby是用REXML库对XML文件进行解析,路径是: rexml/document 

所有方法全部包含在模块 module REXML 中,所以在文件头部引用的时候使用如下格式:
require 'rexml/document'
include REXML

首先我们要打开指定的XML文件:
xmlDoc=File.new('c:\\nodes.xml')
xmlFile=Document.new(xmlDoc)

new
Document类的构造方法,参数可以为一个xml文件的路径,或者一个IO对象。

puts xmlFile.root

输出为:
<root>Root Node<Child1 att1='attvalue1' att2='attvalue2'>Son<Child2>grandson</Child2></Child1></root>

root
返回一个element类型的对象,是该xml的根元素。 注意,这时候不是document对象了,是一个element对象。

puts xmlFile.root.document

输出为:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>Root Node<Child1 att1='attvalue1' att2='attvalue2'>Son<Child2>grandson</Child2></Child1></root>

document
返回包含element类型对象的文档, 注意,这时候是document对象了。

puts xmlFile.root.get_text.value
puts xmlFile.root.get_text
puts xmlFile.root.text
puts xmlFile.root.texts

输出均为:
Root Node

text: 返回第一个text element的string值,为String类
texts:返回的所有text element的集合,为Array类
get_text:返回的是一个REXML::Text对象
value:返回REXML::Text对象的值

puts  XPath.first(xmlFile, "//Child1" )

输出为:
<Child1 att1='attvalue1' att2='attvalue2'>Son<Child2>grandson</Child2></Child1>

使用XPath找到第一个满足Child1的节点,类型为element

XPath.each(xmlFile, "//") { |element| puts element }

返回所有的element

puts xmlFile.get_elements("//Child2")

输出为:
<Child2>grandson</Child2>

使用xpath查找匹配的element

xmlFile.root.xpath

输出为:
/root

显示element的xpath,可以看到具体的xpath路径

puts xmlFile.root.elements[1]

输出为:
<Child1 att1='attvalue1' att2='attvalue2'>Son<Child2>grandson</Child2></Child1>

puts xmlFile.root.elements[1].elements[1]

输出为:
<Child2>grandson</Child2>

以上都是利用index定位element,注意index都是从1开始的,没有0




TAG:

 

评分:0

我来说两句

日历

« 2024-04-27  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 151124
  • 日志数: 185
  • 文件数: 6
  • 建立时间: 2007-08-06
  • 更新时间: 2015-01-06

RSS订阅

Open Toolbar