Best of Ruby Quiz 笔记之三:GEDCOM Parser

关键字:XML  REXML 数组 堆栈

本quiz的目的是将一种给定格式的文件转换成为xml文件。
需要在ruby中操作xml,可以使用REXML标准库

回过头来,看标准答案:
1、ARGF 与$<同义
看看《Programming Ruby第二版》p335上的解释:
$< 返回object,一个可以访问作为命令行参数给出或者$stdin(当没有参数的时候)给出的所有文件的内容对象。 谁能告诉我,介句话是嘛意思??让我翻译成人话试试看,一个对象,当文件名作为命令行参数给出时,可以使用该对象访问这些文件的内容,如果没有参数,那么访问$stdin给出的文件内容。应该是这样吧?
$< 支持的方法和File对象类似。返回的对象可能会改变,因为$<会依次读取命令行上给出的文件。

2、\S 在ruby的正则表达式中匹配除空格之外的任何字符

3、下面这段代码有点trick
# pop off the stack until we get the parent
 while (level+1) < stack.size
  stack.pop
 end
 parent = stack.last
 # create XML tag
 if tag =~ /@.+@/
  el = parent.add_element data
  el.attributes[' id' ] = tag
 else
  el = parent.add_element tag
  el.text = data
 end
 stack.push el
 
 当刚刚初始化完成后,doc所代表的xml中只有一个根节点<gedcom/>,此后开始读取给定的GedCOM格式文件,读到第一个有效的行时,其level为0,while判断为false,置parent为根节点<gedcom/>,然后将当前的节点作为子节点,并分析其level、tag和data,然后添加到doc中,并将该元素添加到stack数组中,再继续向下处理文件中的行。当遇到一行,其level与上一行的level相同时,此时的level+1就小于了stack这个数组的size,上一行数据所形成的节点就是当前行数据对应节点的兄弟节点,那么就将上一行数据从数组中移除,这样可以保证stack数组中的最后一个元素,一直是要当前这一行要添加节点的父节点。这样一直处理到最后处理完成。

4、doc.write($stdout, 0)

write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
输出XML树,并带有缩进可选项indent.这个方法输出完整的XML文档,包括XML声明,doctype声明,任何处理指令。一个争论的焦点是Document是否应该总是输出XML声明(<?xml version='1.0'?>),有人认为这应该由用户决定。如果没有指定的话,REXML不做输出,因为它向类似XML-RPC这样的应用添加了不必要的带宽占用。

output: 输出支持'<< string'的对象,document向其中写入
indent: 整数。如果是-1,不产生缩进;否则,缩进的该数字指定的空格个数,并且子节点将多产生一个额外的缩进。默认-1.
transive: (没看懂,照抄)If transitive is true and indent is >= 0, then the output will be pretty-printed in such a way that the added whitespace does not affect the absolute value of the document — that is, it leaves the value and number of Text nodes in the document unchanged.
ie_hack: (这段原文很有趣,而且简单,建议自己看)Internet Explorer is the worst piece of crap to have ever been written, with the possible exception of Windows itself. Since IE is unable to parse proper XML, we have to provide a hack to generate XML that IE’s limited abilities can handle. This hack inserts a space before the /> on empty tags. Defaults to false 。
 
源代码

posted on 2007-07-23 15:32  小熊bryan  阅读(516)  评论(0编辑  收藏  举报