首页 > 学院 > 开发设计 > 正文

实例解析Ruby程序中调用REXML来解析XML格式数据的用法

2019-10-26 19:29:02
字体:
来源:转载
供稿:网友

REXML 是由 Sean Russell 编写的库。它不是 Ruby 的唯一 XML 库,但它是很受欢迎的一个,并且是用纯 Ruby 编写( NQXML 也是用 Ruby 编写的, 但 XMLParser 封装了用 C 编写的 Jade 库)。 在他的 REXML 概述中,Russell 评论道:
我有这样的问题:我不喜欢令人困惑的 API。有几种用于 Java 实现的 XML 解析器 API。其中大多数都遵循 DOM 或 SAX,并且在基本原理上与不断出现的众多 Java API 非常相似。也就是说,它们看 上去象是由从未使用过他们自己的 API 的理论家设计出来的。 通常,现有的 XML API 都很令人讨厌。他们采用一种被明确设计成非常简单、一流且功能强大的标记语言, 然后用讨厌的、过多的和大型 API 对它进行封装。甚至是为了进行最基本的 XML 树操作,我总是不得不参考 API 文档; 没有任何东西是凭直觉的,而且几乎每个操作都很复杂。
虽然我并不认为它有多么令人心烦,但我同意 Russell 的观点:XML API 对于大多数使用它们的人来说无疑带来了过多的工作量。

示例
看下面的book.xml:

引用

<library shelf="Recent Acquisitions">  <section name="Ruby">   <book isbn="0672328844">   <title>The Ruby Way</title>   <author>Hal Fulton</author>   <description>    Second edition. The book you are now reading.    Ain't recursion grand?   </description>   </book>  </section>  <section name="Space">   <book isbn="0684835509">    <title>The Case for Mars</title>    <author>Robert Zubrin</author>    <description>Pushing toward a second home for the human     race.    </description>   </book>   <book isbn="074325631X">    <title>First Man: The Life of Neil A. Armstrong</title>    <author>James R. Hansen</author>    <description>Definitive biography of the first man on     the moon.    </description>   </book>  </section> </library>

1 Tree Parsing(也就是DOM-like)

我们需要require rexml/document 库,并且include REXML :

require 'rexml/document' include REXML  input = File.new("books.xml") doc = Document.new(input)  root = doc.root puts root.attributes["shelf"]  # Recent Acquisitions  doc.elements.each("library/section") { |e| puts e.attributes["name"] } # Output: # Ruby # Space  doc.elements.each("*/section/book") { |e| puts e.attributes["isbn"] } # Output: # 0672328844 # 0321445619 # 0684835509 # 074325631X  sec2 = root.elements[2] author = sec2.elements[1].elements["author"].text  # Robert Zubrin 

这里要注意的是xml中的属性和值被表示为一个hash,因此我们能够通过attributes[]来提取我们需要的值,元素的值还能通过类似于path的字符串或者整数来取得.其中用整数取的话,是1-based而不是0-based.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表