0

我有一个 Debian 6 设置,我不会接触太多。

$ python --version
Python 2.6.6
$ dpkg --list|grep lxml
ii  python-lxml                        2.2.8-2 

我试图像这样使用 XPath 访问:

import xml.etree.ElementTree as ET
root = ET.parse("a.xml")

for e in root.findall('.//rec/data/field[@name="id"]'):
    print(e.tag + " " + e.attrib.get('name'))

我有一个错误

Traceback (most recent call last):
  File "a.py", line 4, in <module>
    for e in root.findall('.//rec/data/field[@name="id"]'):
  File "/usr/lib/python2.6/xml/etree/ElementTree.py", line 647, in findall
    return self._root.findall(path)
  File "/usr/lib/python2.6/xml/etree/ElementTree.py", line 355, in findall
    return ElementPath.findall(self, path)
  File "/usr/lib/python2.6/xml/etree/ElementPath.py", line 198, in findall
    return _compile(path).findall(element)
  File "/usr/lib/python2.6/xml/etree/ElementPath.py", line 176, in _compile
    p = Path(path)
  File "/usr/lib/python2.6/xml/etree/ElementPath.py", line 93, in __init__
    "expected path separator (%s)" % (op or tag)
SyntaxError: expected path separator ([)

python-lxml 2.2.8 不支持这种 XPath 语法吗?

什么版本支持这个并且与 python 2.6 兼容?

4

1 回答 1

1

代码正在使用ElementTree,而不是lxml.

findall方法ElementTree仅支持 xpath 的子集。(ElementTree 中的 XPath 支持)。

[@attrib="value"]ElementTree API 1.3 也支持。ElementTree API 在 Python 2.7中更新为 1.3 。


替换以下行:

import xml.etree.ElementTree as ET

和:

import lxml.etree as ET

使用lxml.

于 2013-11-15T07:16:17.820 回答