15

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 3

12

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.

Sign up to request clarification or add additional context in comments.

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."
4

My favorite XML processing library for Python is lxml which, because it is a wrapper around libxml2, also supports full XPath.

There is also 4Suite which is more of a pure Python solution.

Comments

4

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

my python is still there. thanks a lot, friend

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.