girファイルの解析python編

seed(JavaScript)でプログラムを書こうとすると、/usr/share/gir-1.0以下のファイルを解析する必要がある。中身はxmlファイルだから文字列扱えるpythonでも使おうと思ったら、pythonにはElementTreeというものがあるらしいので、ちょっと調べてみた。

girファイルは、rootがタグなので、これを表示してみる。

#! /usr/bin/env python

from xml.etree.ElementTree import ElementTree
import sys

gir_tree = ElementTree (file = open (sys.argv[1]))
gir_root = gir_tree.getroot ()
print gir_root.tag

実行すると以下の通り。

$ ./gir_sample00.py /usr/share/gir-1.0/Gtk-2.0.gir 
{http://www.gtk.org/introspection/core/1.0}repository

tagにxmlnsで指定されたnamespaceが追加されているので、xmlも扱い難い感じ。対応するためには、QNameを使えば良いらしい。

#! /usr/bin/env python

from xml.etree.ElementTree import QName

qn = QName ('http://www.gtk.org/introspection/core/1.0', 'repository')
print qn

実行すると以下のようになる。

$ ./gir_sample01.py 
{http://www.gtk.org/introspection/core/1.0}repository

Gtk-2.0.girに記述しているclassを知るには以下のようにすれば良いらしい。

#! /usr/bin/env python

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import QName

import sys

gir_tree = ElementTree (file = open (sys.argv[1]))
gir_root = gir_tree.getroot ()

qn = QName ('http://www.gtk.org/introspection/core/1.0', 'class')
for e in gir_root.getiterator (qn) :
	print e.get ('name')

実行すると以下のようになる。

$ ./gir_sample02.py /usr/share/gir-1.0/Gtk-2.0.gir 
AboutDialog
AccelGroup
…
Widget
Window
WindowGroup

しかし、面倒なので、xslの勉強をしたほうが良いような気がする。