5

本の情報を得るために isbndb.com に接続していますが、その応答は次のようになります。

<?xml version="1.0" encoding="UTF-8"?>
<ISBNdb server_time="2005-02-25T23:03:41">
 <BookList total_results="1" page_size="10" page_number="1" shown_results="1">
  <BookData book_id="somebook" isbn="0123456789">
   <Title>Interesting Book</Title>
   <TitleLong>Interesting Book: Read it or else..</TitleLong>
   <AuthorsText>John Doe</AuthorsText>
   <PublisherText>Acme Publishing</PublisherText>
  </BookData>
 </BookList>
</ISBNdb>

appengine (Python) を使用してこのデータをオブジェクトに変換する最良の方法は何ですか?

isbn 番号 (BookData のタグ) が必要ですが、BookData のすべての子のコンテンツ(タグではなく) も必要です。

4

2 に答える 2

7

etreeを使用してください:)

>>> xml = """<?xml version="1.0" encoding="UTF-8"?>
... <ISBNdb server_time="2005-02-25T23:03:41">
...  <BookList total_results="1" page_size="10" page_number="1" shown_results="1">
...   <BookData book_id="somebook" isbn="0123456789">
...    <Title>Interesting Book</Title>
...    <TitleLong>Interesting Book: Read it or else..</TitleLong>
...    <AuthorsText>John Doe</AuthorsText>
...    <PublisherText>Acme Publishing</PublisherText>
...   </BookData>
...  </BookList>
... </ISBNdb>"""

from xml.etree import ElementTree as etree
tree = etree.fromstring(xml)

>>> for book in tree.iterfind('BookList/BookData'):
...     print 'isbn:', book.attrib['isbn']
...     for child in book.getchildren():
...             print '%s :' % child.tag, child.text
... 
isbn: 0123456789
Title : Interesting Book
TitleLong : Interesting Book: Read it or else..
AuthorsText : John Doe
PublisherText : Acme Publishing
>>> 

voila;)
于 2011-01-07T18:46:56.233 に答える
0

BeautifulSoup という優れた Python モジュールがあります。XML 解析には BeautifulStoneSoup クラスを使用します。

詳細: http://www.crummy.com/software/BeautifulSoup/documentation.html

于 2011-01-07T18:41:15.680 に答える