我应该使用哪个Python XML库?

时间:2010-05-25 20:52:47

标签: python lxml celementtree

我将处理项目的XML文件。我之前决定使用lxml,但在阅读了要求后,我认为ElemenTree会更好用于我的目的。

必须处理的XML文件是:

  1. 体积小。通常< 10 KB。

  2. 没有名称空间。

  3. 简单的XML结构。

  4. 考虑到XML的小尺寸,内存不是问题。我唯一关心的是快速解析。

    我该怎么办?大多数情况下,我看到人们推荐lxml,但考虑到我的解析要求,我是否真的能从中受益,或者ElementTree会更好地满足我的目的?

3 个答案:

答案 0 :(得分:2)

正如其他人所指出的,lxml实现了ElementTree API,因此如果您需要更好的性能或更高级的功能,那么从ElementTree开始安全并迁移到lxml。

使用ElementTree的一大优势是,如果它满足您的需求,那就是从Python 2.5开始它是part of the Python standard library,它减少了外部依赖性和处理编译/安装C模块的(可能)头痛的问题

答案 1 :(得分:0)

lxml基本上是ElementTree的超集,因此您可以从ElementTree开始,然后如果您遇到性能或功能问题,那么您可以更改为lxml。

性能问题只能由您使用自己的数据进行研究

答案 2 :(得分:0)

我推荐自己的食谱

XML to Python data structure « Python recipes « ActiveState Code

它不会加速解析。但它提供了真正的本机对象样式访问。

>>> SAMPLE_XML = """<?xml version="1.0" encoding="UTF-8"?>
... <address_book>
...   <person gender='m'>
...     <name>fred</name>
...     <phone type='home'>54321</phone>
...     <phone type='cell'>12345</phone>
...     <note>&quot;A<!-- comment --><![CDATA[ <note>]]>&quot;</note>
...   </person>
... </address_book>
... """
>>> address_book = xml2obj(SAMPLE_XML)
>>> person = address_book.person


person.gender        -> 'm'     # an attribute
person['gender']     -> 'm'     # alternative dictionary syntax
person.name          -> 'fred'  # shortcut to a text node
person.phone[0].type -> 'home'  # multiple elements becomes an list
person.phone[0].data -> '54321' # use .data to get the text value
str(person.phone[0]) -> '54321' # alternative syntax for the text value
person[0]            -> person  # if there are only one <person>, it can still
                                # be used as if it is a list of 1 element.
'address' in person  -> False   # test for existence of an attr or child
person.address       -> None    # non-exist element returns None
bool(person.address) -> False   # has any 'address' data (attr, child or text)
person.note          -> '"A <note>"'