pythonxml-parsingpython-2.7elementtreeiterparse

Python: xPath not available in ElementTree


I am trying to parse iTunes Playlist by using iterparse() of ElementTree but getting following error:

AttributeError: 'Element' object has no attribute 'xpath'

Code is given below:

import xml.etree.ElementTree as ET
context = ET.iterparse(file,events=("start", "end"))
    # turn it into an iterator
    context = iter(context)
    # get the root element
    event, root = context.next()
    for event, elem in context:
        z = elem.xpath(".//key")
        elem.clear()
        root.clear()
    print z

What I am doing wrong? File is too big so I have to use iterparse() anyway.


Solution

  • xml.etree.ElementTree provides limited support for XPath expressions for its Element class find, findall and findtext methods (there's no xpath method: that's why you are getting an error).

    Also, if you call clear() on an element to conserve used memory, you need to do it only after you've finished processing the element and all its children.

    Therefore, you need to to change your code to something similar to the following:

    for event, elem in context:
        for child in elem.findall(".//key"):
            # process child
        elem.clear()
        root.clear()