使用xpath通过python中的两个属性定位节点

Use xpath to locate nodes through two attributes in python

我想用Xpath通过两个属性来定位某个节点。 这是一个例子:

from xml.etree import ElementTree as ET

xmldata="""
<postlinks>
  <row Id="19" CreationDate="2010-04-26T02:59:48.130" PostId="109" RelatedPostId="32412" LinkTypeId="1" />
  <row Id="37" CreationDate="2010-04-26T02:59:48.600" PostId="1970" RelatedPostId="617600" LinkTypeId="1" />
  <row Id="42" CreationDate="2010-04-26T02:59:48.647" PostId="2154" RelatedPostId="2451138" LinkTypeId="1" />
</postlinks>
"""
import io
tree = ET.parse(io.StringIO(xmldata))
nodes = tree.find(".//row[@PostId='109' and @RelatedPostId='32412']")
print(nodes.attrib)

我想通过 PostId='109' 和 RelatedPostId='32412' 定位到 Id='19' 的节点。

但是我得到这个错误:

Traceback (most recent call last):
  File "D:\anaconda\envs\PRTagRec\lib\xml\etree\ElementPath.py", line 272, in iterfind
    selector = _cache[cache_key]
KeyError: (".//row[@PostId='109' and @RelatedPostId='32412']", None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/pythonProject/LabelLink/temp.py", line 20, in <module>
    nodes = tree.find(".//row[@PostId='109' and @RelatedPostId='32412']")
  File "D:\anaconda\envs\PRTagRec\lib\xml\etree\ElementTree.py", line 653, in find
    return self._root.find(path, namespaces)
  File "D:\anaconda\envs\PRTagRec\lib\xml\etree\ElementPath.py", line 307, in find
    return next(iterfind(elem, path, namespaces), None)
  File "D:\anaconda\envs\PRTagRec\lib\xml\etree\ElementPath.py", line 286, in iterfind
    selector.append(ops[token[0]](next, token))
  File "D:\anaconda\envs\PRTagRec\lib\xml\etree\ElementPath.py", line 242, in prepare_predicate
    raise SyntaxError("invalid predicate")
SyntaxError: invalid predicate

但是当我使用一个属性时,例如 nodes = tree.find(".//row[@PostId='109']")nodes = tree.find(".//row[@RelatedPostId='32412']"),我得到那个节点。 {'Id': '19', 'CreationDate': '2010-04-26T02:59:48.130', 'PostId': '109', 'RelatedPostId': '32412', 'LinkTypeId': '1'}

我该怎么办?

附加谓词以形成逻辑与。

from xml.etree import ElementTree as ET

xmldata="""
<postlinks>
  <row Id="19" CreationDate="2010-04-26T02:59:48.130" PostId="109" RelatedPostId="32412" LinkTypeId="1" />
  <row Id="37" CreationDate="2010-04-26T02:59:48.600" PostId="1970" RelatedPostId="617600" LinkTypeId="1" />
  <row Id="42" CreationDate="2010-04-26T02:59:48.647" PostId="2154" RelatedPostId="2451138" LinkTypeId="1" />
</postlinks>
"""
import io
tree = ET.parse(io.StringIO(xmldata))
nodes = tree.find(".//row[@PostId='109'][@RelatedPostId='32412']")
print(nodes.attrib)