如何利用Ruby来解析XML

前段时候做个小工具,把每天的svn日志抽出来取,再把必要的信息通过邮件方式知会大家。

最后采用的技术是ruby on rails 的rake。实现过程中必须要用ruby解析xml文件。上网查了一些相关的资料,方法有很多,在这里做一个汇总:

1. 使用REXML
doc = REXML::Document.new(File.open(file_path))
doc.elements.each(’log/logentry’) do |ele|
author_ele = ele.get_elements(’author’)
msg_ele = ele.get_elements(’msg’)
end

2. 使用XmlSimple

xml_file = File.open(file_path)
data = XmlSimple.xml_in(xml_file)
data['logentry'].each do |item|
item['msg']
item['author']

end

3. 使用Hpricot

Hpricot是一个HTML解释的库,支持XML。Hpricot允许开发者通过CSS-selectors和X-Path访问html元素,因此你很轻松就可以明确目标标记,还有它是用C语言写的,因此相当快。

安装方法:gem install hpricot

# load the RedHanded home page

doc = Hpricot(open(”http://redhanded.hobix.com/index.html”))

# change the CSS class on links

(doc/”span.entryPermalink”).set(”class”, “newLinks”)

# remove the sidebar (doc/”#sidebar”).remove

# print the altered HTML

puts doc

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

good pratice!

我比较喜欢用rubyful_soup处理xml

Fv1Xc0

发表评论

(必填)

(必填)


MC Inside