如何在Python 3.6中使用LXML find()通过变量替换谓词值

时间:2019-01-12 00:42:03

标签: python-3.x xpath lxml

我是Python编码的新手。我能够创建输出XML文件。我想使用一个包含字符串值的变量,并将其传递给“ find()”的“谓词”。这可以实现吗?如何进行这项工作?

我正在将LXML包与Python 3.6一起使用。下面是我的代码。在代码末尾注释了问题区域。

JsonConfig['attribute-names'] = ['id','idref'];
JsonConfig['attribute-names'] = ('id','idref');

2 个答案:

答案 0 :(得分:3)

正如Daniel Haley所说-您在@Name={subs}中缺少单引号。

以下一行对我有用:

x = root.find("./FirstNode/SecondNode[@Name='{subs}']".format(subs=NewValue))

由于您使用的是 Python 3.6 ,因此可以使用f-strings

x = root.find(f"./FirstNode/SecondNode[@Name='{NewValue}']")

答案 1 :(得分:0)

解决此问题的“正确”方法是使用find()不支持的How to create a library with Qt...(因此,标准库中的xml.etree也不受支持) ),但XPath variables

NewValue = "AJL's Second Node" # Uh oh, that apostrophe is going to break something!!
x_list = root.xpath("./FirstNode/SecondNode[@Name=$subs]", subs=NewValue)
x = x_list[0]

这避免了您可能因引用和转义而遇到的任何问题。


此方法的主要警告是名称空间支持,因为它不使用find的括号语法。

x = root.find("./{foobar.xsd}FirstNode")
# Brackets are doubled to avoid conflicting with `.format()`
x = root.find("./{{foobar.xsd}}FirstNode/SecondNode[@Name='{subs}']".format(subs=NewValue))

相反,您必须在单独的字典中指定它们:

ns_list = {'hello':'foobar.xsd'}
x_list = root.xpath("./hello:FirstNode/SecondNode[@Name=$subs]", namespaces=ns_list , subs=NewValue)
x = x_list[0]