Is it possible to use XPath Query in Python while processing XML. I am using minidom which doesn't support that. Is there any other module for that?
3 Answers
http://docs.python.org/library/xml.etree.elementtree.html
etree supports XPath queries, just like lxml.
etree is included in the standard library, but lxml is faster.
1 Comment
Support for XPath is limited in ElementTree though, as quoted in the Python 3 docs: "This module provides limited support for XPath expressions for locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module."
ElementTree is included. Under 2.6 and below its xpath is pretty weak, but in 2.7+ much improved:
import xml.etree.ElementTree as ET
root = ET.parse(filename)
result = ''
# How to make decisions based on attributes even in 2.6
for elem in root.findall('.//child/grandchild'):
if elem.attrib.get('name') == 'foo':
result = elem.text
break
1 Comment
alex
my python is still there. thanks a lot, friend