免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6715 | 回复: 1
打印 上一主题 下一主题

Ruby,Rails关于XML的处理的小结 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-28 08:01 |只看该作者 |倒序浏览
REXML是处理,解析XML的包,是Ruby自带的包。因为支持XPath表达式的查询,所以用来查询结点,解析XML非常方便。

通过最近做项目对解析和处理XML有如下认识:

REXML功能非常强大,但是使用上不是特别的方便,Rails把它封装了一下,生成XML非常容易,代码也很简单直观。

但对于解析XML,用REXML就可以了,十分方便并且灵活。转载自:ruby

生成XML,用Rails的Builder::XmlMarkup比较方便(rjs模板好像就用这个,由于项目需要生成XML字符后直接传给另一个方法,所以用不了rjs)

以下示例引用<<rogrammingRuby 1.9>>

  1. <classes language="ruby">
  2.        <class name="Numeric">
  3.          Numeric represents all numbers.
  4.          <class name="Float">
  5.             Floating point numbers have a fraction and a mantissa.
  6.          </class>
  7.          <class name="Integer">
  8.             Integers contain exact integral values.
  9.             <class name="Fixnum">
  10.                Fixnums are stored as machine ints.
  11.             </class>
  12.             <class name="Bignum">
  13.                Bignums store arbitraty-sized integers.
  14.             </class>
  15.          </class>
  16.        </class>
  17.      </classes>
复制代码

  1. require 'rexml/document'
  2.      xml = REXML::Document.new(File.open("demo.xml"))
  3.    
  4.      puts "Root element: #{xml.root.name}"
  5.      puts "\nThe names of all classes"
  6.      xml.elements.each("//class") {|c| puts c.attributes["name"] }
  7.      puts "\nThe description of Fixnum"
  8.      p xml.elements["//class[@name='Fixnum']"].text
  9.      produces:
  10.      Root element: classes
  11.      The names of all classes
  12.      Numeric
  13.      Float
  14.      Integer
  15.      Fixnum
  16.      Bignum
  17.      The description of Fixnum
  18.      "\n             Fixnums are stored as machine ints.\n         "
复制代码


以下示例来源Rails API Builder::XmlMarkup
  1. xm.instruct!                   # <?xml version="1.0" encoding="UTF-8"?>
  2.   xm.html {                      # <html>
  3.     xm.head {                    #   <head>
  4.       xm.title("History")        #     <title>History</title>
  5.     }                                       #   </head>
  6.     xm.body {                     #   <body>
  7.       xm.comment! "HI"           #     <! -- HI -->
  8.       xm.h1("Header")            #     <h1>Header</h1>
  9.       xm.p("paragraph")          #     <p>paragraph</p>
  10.     }                                      #   </body>
  11.   }                                        # </html>
复制代码

论坛徽章:
0
2 [报告]
发表于 2009-08-28 16:39 |只看该作者
用libxml可以大幅度提高对XML解析速度,对于超过1M以上的XML解析速度大大高于REXML。
http://libxml.rubyforge.org/
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP