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

2024-10-01 11:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在连接到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所有子级的内容(与标记相反)。在


Tags: 标记comtitlepageresultsisbnbookinteresting
2条回答

有一个很好的Python模块叫做beauthoupan。使用BeautifullsToNesUp类进行XML解析。在

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

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

相关问题 更多 >