Python: xPath not available in ElementTree

孤人 提交于 2021-02-19 04:45:35

问题


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.


回答1:


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()


来源:https://stackoverflow.com/questions/13455672/python-xpath-not-available-in-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!