ruby 使用REXML解析xml

REXML 是一个完全用ruby写的processor ,他有多种api,其中两个经典的api是通过DOM-like 和SAX-like 来进行区分的。第一种是将整个文件读进内存,然后存储为一个分层的形式(也就是一棵树了).而第二种是"parse as you go",当你的文件很大,并且内存受到限制的时候,比较适合用这种。

看下面的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 :

 

  1. require 'rexml/document'  
  2. include REXML   
  3.   
  4. input = File.new("books.xml")   
  5. doc = Document.new(input)   
  6.   
  7. root = doc.root   
  8. puts root.attributes["shelf"]      # Recent Acquisitions   
  9.   
  10. doc.elements.each("library/section") { |e| puts e.attributes["name"] }   
  11. # Output:   
  12. #   Ruby   
  13. #   Space   
  14.   
  15. doc.elements.each("*/section/book") { |e| puts e.attributes["isbn"] }   
  16. # Output:   
  17. #   0672328844  
  18. #   0321445619  
  19. #   0684835509  
  20. #   074325631X   
  21.   
  22. sec2 = root.elements[2]   
  23. author = sec2.elements[1].elements["author"].text       # Robert Zubrin  

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

2  Stream Parsing(也就是SAX-like Parsing)

这边使用了一个小技巧,那就是定义了一个listener 类,它将会在parse的时候被回调:

 

  1. require 'rexml/document'  
  2. require 'rexml/streamlistener'  
  3. include REXML   
  4.   
  5. class MyListener   
  6.   include REXML::StreamListener   
  7.   def tag_start(*args)   
  8.     puts "tag_start: #{args.map {|x| x.inspect}.join(', ')}"  
  9.   end   
  10.   
  11.   def text(data)   
  12.     return if data =~ /^\w*$/     # whitespace only   
  13.     abbrev = data[0..40] + (data.length > 40 ? "..." : "")   
  14.     puts "  text   :   #{abbrev.inspect}"  
  15.   end   
  16. end   
  17.   
  18. list = MyListener.new  
  19. source = File.new "books.xml"  
  20. Document.parse_stream(source, list)  

这 里介绍一下StreamListener 模块,这个模块它提供了几个空的回调方法,因此你可以为了实现你自己的功能而覆盖它.当parser 进入一个tag时,就会调用tag_start方法.而text方法也是类似的,他只不过是当读取到数据时会被回调,它的输出是这样的:

 

  1. tag_start: "library", {"shelf"=>"Recent Acquisitions"}   
  2. tag_start: "section", {"name"=>"Ruby"}   
  3. tag_start: "book", {"isbn"=>"0672328844"}   
  4. tag_start: "title", {}   
  5.   text   :   "The Ruby Way"  
  6. .........................................  

3 XPath

REXML通过XPath 类来提供Xpath的支持. 它也同时支持DOM-like和SAX-like .还是前面的那个xml文件,我们使用Xpath可以这样做:

 

  1. book1 = XPath.first(doc, "//book")    # Info for first book found   
  2. p book1   
  3.   
  4. # Print out all titles   
  5. XPath.each(doc, "//title") { |e| puts e.text }   
  6.   
  7. # Get an array of all of the "author" elements in the document.   
  8. names = XPath.match(doc, "//author").map {|x| x.text }   
  9. p names  

输出是类似于下面的:

 

  1. <book isbn='0672328844'> ... </>   
  2. The Ruby Way   
  3. The Case for Mars   
  4. First Man: The Life of Neil A. Armstrong   
  5. ["Hal Fulton", "Robert Zubrin", "James R. Hansen"] 

原文链接:http://blog.163.com/fu_guiyan/blog/static/32024826200912811718679/

posted on 2014-12-18 14:15  陆星儿  阅读(740)  评论(0)    收藏  举报

导航