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

5 投票
2 回答
3326 浏览
提问于 2025-04-16 09:35

我正在连接 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 所有子项的 内容(而不是标签)。

2 个回答

0

有一个很棒的Python模块叫做BeautifulSoup。你可以用BeautifulStoneSoup这个类来解析XML文件。

更多信息请查看: http://www.crummy.com/software/BeautifulSoup/documentation.html

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;)

撰写回答