我将处理项目的XML文件。我以前决定使用lxml,但在阅读要求后,我认为ElemenTree会更适合我的目的。我应该使用哪个Python XML库?
有要处理的XML文件是:
体积小。通常< 10 KB。
没有名称空间。
简单的XML结构。
由于XML尺寸较小,内存不是问题。我唯一关心的是快速解析。
我该怎么办?大多数情况下,我看到人们推荐lxml,但考虑到我的解析要求,我真的愿意从中受益吗?或者ElementTree会更好地服务我的目的?
我将处理项目的XML文件。我以前决定使用lxml,但在阅读要求后,我认为ElemenTree会更适合我的目的。我应该使用哪个Python XML库?
有要处理的XML文件是:
体积小。通常< 10 KB。
没有名称空间。
简单的XML结构。
由于XML尺寸较小,内存不是问题。我唯一关心的是快速解析。
我该怎么办?大多数情况下,我看到人们推荐lxml,但考虑到我的解析要求,我真的愿意从中受益吗?或者ElementTree会更好地服务我的目的?
正如其他人所指出的那样,LXML实现了ElementTree的API,让你的安全与ElementTree的起步和迁移限于lxml如果你需要更好的性能或更高级的功能。
如果满足您的需求,使用ElementTree的一大优势是,从Python 2.5开始,它是part of the Python standard library,它减少了外部依赖和处理编译/安装C模块的(可能)头痛。
lxml基本上是ElementTree的超集,因此您可以从ElementTree开始,然后如果您有性能或功能问题,则可以更改为lxml。
性能问题只能由您使用自己的数据,来研究
我推荐我自己的食谱
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>"A<!-- comment --><![CDATA[ <note>]]>"</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>"'