require 'rexml/document'
xml = REXML::Document.new(open("foo.xml"))
nodes = xml.get_elements("/foo/bar/")
nodes.each{|a| puts a.text}
xml = REXML::Document.new(io)
xml = REXML::Document.new(string)
nodes = xml.get_elements(xpath) # xpathによる検索
node = xml.elements[xpath] # 最初の要素を取得
nodes = node.get_elements(xpath) # サブツリー以下を検索
tag = node.name # 名前(タグ名など?)
href = node.attributes['href'] # attribute
formatter = REXML::Formatters::Pretty.new
puts formatter.write(xml.root,"")
- 色々勝手にテキストを変えられてしまうので、テキストを保存したい場合は継承して使う
class MyPretty < REXML::Formatters::Pretty
def wrap_text(node, output)
output << node.to_s
end
end
最終更新:2012年03月19日 19:41