Rubyの正規表現によるXMLの解析
以前、 Rubyの正規表現によるXMLの解析 という記事を書きましたが、今回それをもう少し汎用化した xmlhash.rb というライブラリを作ってみま した。
xmlhash.rb は厳格に XML を解析するものではなく、解析できない XML もあ ると思いますが、特定用途には簡単に使うことができる軽量なライブラリです。
例
xmlhash.rb は XML 文字列を Ruby の Hash や Array を組み合わせた構造に 変換するライブラリです。
たとえば、以下のような内容の export.xml というファイルがあるとします。
<?xml version="1.0" encoding="utf-8"?>
<opml version="1.0">
<head>
<title>Subscriptions</title>
<dateCreated>Sat, 17 Dec 2005 00:57:22 GMT</dateCreated>
<ownerName></ownerName>
</head>
<body>
<outline title="Subscriptions">
<outline title="Bloglines | News"
htmlUrl="http://www.bloglines.com"
type="rss" xmlUrl="http://www.bloglines.com/rss/about/news" />
<outline title="pylori*style" htmlUrl="http://tam.qmix.org/"
type="rss" xmlUrl="http://tam.qmix.org/index.rdf" />
</outline>
</body>
</opml>
xmlhash.rb を使ってこれを解析するプログラムは以下のようになります。
require 'xmlhash'
require 'pp'
xh = XMLHash.new
xml_str = open('export.xml').read
res = xh.parse xml_str
pp res
結果は以下のようになります。
{"opml"=>
{"head"=>
{"ownerName"=>"",
"title"=>"Subscriptions",
"dateCreated"=>"Sat, 17 Dec 2005 00:57:22 GMT"},
"body"=>
{"outline"=>
{"title"=>"Subscriptions",
"outline"=>
[{"xmlUrl"=>"http://www.bloglines.com/rss/about/news",
"title"=>"Bloglines | News",
"type"=>"rss",
"htmlUrl"=>"http://www.bloglines.com"},
{"xmlUrl"=>"http://tam.qmix.org/index.rdf",
"title"=>"pylori*style",
"type"=>"rss",
"htmlUrl"=>"http://tam.qmix.org/"}]}},
"version"=>"1.0"}}
XML のタグ名がハッシュのキーに、対応する属性や要素が値になります。

Keyword(s):
References:[FrontPage]