Google App Engine で XML をパースする方法

誤解があるといけないので書きますが,「Google App EngineにXMLパーサが入っていない」ということはありません。 ElementTree という Python 標準モジュールがふつうに使えるので,特に App Engine だからといって意識する必要はありません。Pythonで書かれたpure Python版とCのライブラリを利用したものがありますが,どちらでもOKです。好きな方をインポートしてください。

pure Python版
from xml.etree import ElementTree
Cライブラリ版
from xml.etree import cElementTree

例えば,Twitter の XML を取得してきて,パースして名前と本文を表示するのは,こんな感じでできます。簡単ですね。

import xml.etree.cElementTree as etree
from google.appengine.api import urlfetch

url = 'http://twitter.com/statuses/public_timeline.xml'
xml = urlfetch.fetch(url).content
dom = etree.fromstring(xml)

for st in dom.findall('./status'):
    name = st.findtext('user/screen_name').encode('utf-8')
    msg = st.findtext('text').encode('utf-8')
    print "%s: %s\n" % (name, msg)

簡単に説明すると, status エレメントでループして,その中から screen_name と text エレメントのテキストを取り出して表示しています。ちなみに,Twitter public timeline の XML はこんな感じです。

<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array">
  <status>
    <created_at>Fri Apr 11 14:36:25 +0000 2008</created_at>
    <id>787211133</id>
    <text>ニコニコ ドウガ ヲ ミテイマース</text>
    <source><a href="http://twitterfeed.com">twitterfeed</a></source>

    <truncated>false</truncated>
    <in_reply_to></in_reply_to>
    <in_reply_to_user_id></in_reply_to_user_id>
    <user>
      <id>7999382</id>
      <name>fileunder</name>
      <screen_name>fileunder</screen_name>

      <location>Amersfoort</location>
      <description>Regelneef van FileUnder. Al lijkt het soms ook wel eens een vorm van ehm ehm nu ja zoiets.</description>
      <profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/28244052/DSC00034_normal.jpg</profile_image_url>
      <url>http://www.fileunder.nl</url>
      <protected>false</protected>
      <followers_count>76</followers_count>

    </user>
  </status>
  <status>
  …
  </status>
</statuses>

# 本当は, lxml を使えると最高なんですけどね…



Leave a comment





このエントリーのはてなブックマーク (-)