使用Python解析Appengine中的xml的最佳方法

jcu*_*nod 5 python google-app-engine xml-deserialization

我正在连接到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>
Run Code Online (Sandbox Code Playgroud)

使用appengine(Python)将这些数据转换为对象的最佳方法是什么?

我需要isbn数字(BookData中的标签),但我还需要BookData所有子节点的内容(而不是标签).

vir*_*ilo 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;)
Run Code Online (Sandbox Code Playgroud)

  • 是的,在Python 2.7中添加了`iterfind()`方法.GAE [支持Python 2.5](http://code.google.com/intl/sv/appengine/kb/general.html#language).要使@virhilo的解决方案在2.5中工作,用`findall()`替换`iterfind()`. (3认同)