XPath按子值搜索元素

时间:2014-10-29 12:11:21

标签: python xml xpath

我有一个具有以下结构的XML:

<?xml version="1.0" encoding="iso-8859-2"?>
<partners>
  <partner>
    <id>001</id>
    ...
  </partner>
  <partner>
    <id>002</id>
    ...
  </partner>
  ...
</partners>

我想使用XPath搜索具有给定ID的合作伙伴。我正在使用python xml.etree,但在这种情况下这可能无关紧要。到目前为止,我正在尝试:'./partner[/id = "001"]'找到ID = 001的合作伙伴:

for e in doc.findall('./partner[/id = "001"]'): print e

这会引发语法错误SyntaxError: expected path separator ([),完整堆栈跟踪如下:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  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 2.6.8版本。在这种情况下,文档略有不同:https://docs.python.org/release/2.6.8/library/xml.etree.elementtree.html。不,我不能更新python版本,不幸的是......

1 个答案:

答案 0 :(得分:1)

XPath support of xml.etree.ElementTree is limited。使用lxml怎么样?使用xpath method

>>> x = '''<?xml version="1.0" encoding="iso-8859-2"?>
... <partners>
...   <partner>
...     <id>001</id>
...   </partner>
...   <partner>
...     <id>002</id>
...   </partner>
... </partners>'''
>>>
>>> import lxml.etree
>>> root = lxml.etree.fromstring(x)
>>> root.xpath('.//partner[id/text()="001"]')
[<Element partner at 0x2e29090>]