python-3.x - 如何在 Python 3.6 中使用 LXML find() 用变量替换谓词值

标签 python-3.x xpath lxml

我是 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/

相关文章:

python - 使用 lxml 在 Python 中漂亮地格式化 xml 文件

python - 如何使用 Python 库验证 XML 文件时出现多个错误?

python - 字典生成器中的多个 'for' 循环

不是 **kwargs 而是在函数调用本身上使用的 Python 双星号

xml - 如何使用xslt2.0在xml文件中以相同顺序获取特定的xml元素值?

python - 使用 lxml 和 xpath 解析 Html

python - 使用 gpsd 和 python 改变更新率

python - BeautifulSoup 解析器添加了不必要的结束 html 标签

xslt - 名称位于其他一些元素名称之中的第一个元素的 XPATH

xml - XSLT 计算子节点