首页 > 解决方案 > 如何在 python 中转义字符串以用作 xpath 键

问题描述

我在python中遇到了这个关键错误

  KeyError: ("./note/[@player='Ba'g']",)

使用时

  player = "Ba'g"
  xpathstring = "./note/[@player='{}']".format(player.replace("'","\'"))
  p = xmltree.find(xpathstring)

所以我想知道如何转义字符串,以便我可以在 xmltree 中用作 xpath 搜索字符串

标签: pythonxmlxpath

解决方案


当前,您正在将字符串传递"./note/[@player='Ba'g']"给 find 函数。

似乎没有办法正确转义 xpath 中的单引号

但是,您可以从单引号切换到双引号。尝试:

 xpathstring = "./note/[@player=\"{}\"]".format(player)

这是链接问题中建议的解决方案。


推荐阅读