我是 Python 编码新手。我能够创建输出 XML 文件。我想使用一个保存字符串值的变量并将其传递给“find()”的“谓词”。这是可以实现的吗?如何做到这一点?
我正在使用 Python 3.6 的 LXML 包。下面是我的代码。问题区域在代码末尾进行了注释。
import lxml.etree as ET
# Create root element
root = ET.Element("Base", attrib={'Name': 'My Base Node'})
# Create first child element
FirstElement = ET.SubElement(root, "FirstNode", attrib={'Name': 'My First Node', 'Comment':'Hello'})
# Create second child element
SecondElement = ET.SubElement(FirstElement, "SecondNode", attrib={'Name': 'My Second Node', 'Comment': 'World'})
# Create XML file
XML_data_as_string = ET.tostring(root, encoding='utf8')
with open("TestFile.xml", "wb") as f:
f.write(XML_data_as_string)
# Variable to substitute in second portion of predicate
NewValue = "My Second Node"
# #### AREA OF PROBLEM ###
# Question. How to pass variable 'NewValue' in the predicate?
# Gives "SyntaxError: invalid predicate"
x = root.find("./FirstNode/SecondNode[@Name={subs}]".format(subs=NewValue))
# I commented above line and reexecuted the code with this below line
# enabled. It gave "ValueError: empty namespace prefix must be passed as None,
# not the empty string"
x = root.find("./FirstNode/SecondNode[@Name=%s]", NewValue)
最佳答案
如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}']")
关于python-3.x - 如何在 Python 3.6 中使用 LXML find() 用变量替换谓词值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54155796/