简体   繁体   English

如何在 python 中转义字符串以用作 xpath 密钥

[英]How to escape a string in python to use as an xpath key

I got this key error in python我在 python 中遇到了这个关键错误

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

when using使用时

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

So I am wondering how to escape the string such that I can use as an xpath search string in an xmltree所以我想知道如何转义字符串,以便我可以在 xmltree 中用作 xpath 搜索字符串

Currently you are passing the string "./note/[@player='Ba'g']" to the find function.目前,您正在将字符串"./note/[@player='Ba'g']"传递给查找 function。

There seems to be no way to properly escape single quotes in xpath .似乎没有办法正确转义 xpath 中的单引号

However, you can switch from single to double quotes.但是,您可以从单引号切换到双引号。 Try:尝试:

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

This is the suggested solution in the linked issue.这是链接问题中建议的解决方案。

I propose this workaround (XPath 2.0):我提出了这个解决方法(XPath 2.0):

Assuming you have an element with an attribute which contains single and double quotation marks:假设您有一个包含单引号和双引号的属性的元素:

<div>
<note player="Ba&apos;g&quot;N Toast">foo</note>
</div>

To select this node with XPath and a fixed variable we can use something like:对于 select 这个节点,我们可以使用 XPath 和一个固定变量,例如:

import  re
player = '''Ba'g"N Toast'''
result = re.sub(r"(.+)", r"'\1'",player.replace("'","',codepoints-to-string(39),'").replace('"',"',codepoints-to-string(34),'"))
xpathstring = "//note[@player=concat({})]".format(result)
p = xmltree.find(xpathstring)

We replace ' and " with their codepoints equivalents. The result will feed the concat function in the XPath expression.我们将'"替换为其代码点等效项。结果将在 XPath 表达式中提供concat function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM