如何解决使用xpath通过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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。