2009-08-21 47 views

回答

7

http://docs.python.org/library/xml.etree.elementtree.html

etree支持XPath查询,就像LXML。

etree包含在标准库,但LXML更快。

+1

支持的ElementTree是有限的,虽然,如所报[Python的3个文档(https://docs.python.org/3 /library/xml.etree.elementtree.html#xpath-support):“该模块对XPath表达式在树中定位元素提供了有限的支持,目标是支持缩写语法的一小部分;完整的XPath引擎是在模块的范围之外。“ – 2015-04-03 19:28:54

2

为Python我最喜欢的XML处理库是lxml它,因为它是围绕libxml2的包装,还支持完整的XPath。

还有4Suite这是更纯的Python溶液。

1

ElementTree包含在内。在2.6及其以下的XPath是相当薄弱,但在2.7 much improved

XPath的
import xml.etree.ElementTree as et 
root = et.parse(filename) 
result = '' 

# How to make decisions based on attributes even in 2.6 
for e in root.findall('.//child/grandchild'): 
    if e.attrib.get('name') == 'foo': 
     result = e.text 
     break