【问题标题】:Best way to parse xml in Appengine with Python使用 Python 在 Appengine 中解析 xml 的最佳方法
【发布时间】:2011-06-05 10:52:20
【问题描述】:

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

【问题讨论】:

    标签: python google-app-engine xml-deserialization


    【解决方案1】:

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

    【讨论】:

    • 我实际上是在尝试将 xml 数据转换为 Book.isbn 和 Book.title 等对象,但我会接受,因为我认为我不清楚,这似乎是最接近的我会得到。我只是将一个 switch-case(使用 if-else)推到 for 循环中并生成一个类似的对象,所以如果你有更好的想法,请分享。
    • 你可以这样做: class Book(object): def __init__(self, isbn, title, title_long): self.isbn = isbn self.title = title self.title_long = title_long # etc. books = [] for book in tree.iterfind('BookList/BookData'): book_obj = Book(book.attrib['isbn'], book.find('Title'), book.find('TitleLong')) #等等。 book.add(book_obj)
    • 非常感谢 - 顺便说一下,您上面的代码需要进行一些修改.find 它遍历孩子而不需要得到孩子。不过非常感谢
    • 是的,iterfind() 方法是在 Python 2.7 中添加的。盖伊supports Python 2.5。要使 @virhilo 的解决方案在 2.5 中工作,请将 iterfind() 替换为 findall()
    • 我使用 find() 是因为在通过 isbn 搜索时,api 最多会返回一个值(因为它是唯一的)。谢谢
    【解决方案2】:

    有一个很棒的 Python 模块,叫做 BeautifulSoup。使用 BeautifulStoneSoup 类进行 XML 解析。

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

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2014-09-02
      • 2015-08-21
      • 2011-05-03
      • 1970-01-01
      • 2020-03-20
      相关资源
      最近更新 更多