简体   繁体   English

使用Python在XML中进行XPath查询

[英]XPath Query in XML using Python

Is it possible to use XPath Query in Python while processing XML. 是否可以在处理XML时在Python中使用XPath Query。 I am using minidom which doesn't support that. 我正在使用不支持它的minidom。 Is there any other module for that? 那还有其他模块吗?

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

etree supports XPath queries, just like lxml. etree支持XPath查询,就像lxml一样。

etree is included in the standard library, but lxml is faster. etree包含在标准库中,但lxml更快。

My favorite XML processing library for Python is lxml which, because it is a wrapper around libxml2, also supports full XPath. 我最喜欢的Python XML处理库是lxml ,因为它是libxml2的包装器,所以也支持完整的XPath。

There is also 4Suite which is more of a pure Python solution. 还有4Suite ,它更像是一个纯Python解决方案。

ElementTree is included. ElementTree包括在内。 Under 2.6 and below its xpath is pretty weak, but in 2.7 much improved : 在2.6以下,它的xpath非常弱,但在2.7中有很大改进

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM