Python lxml 库,制作以变量作为属性名的元素

Python lxml library, making element with variables as attribute names

我正在尝试根据 excel 电子表格中的信息动态创建 .xml 文件。

基本上我想做的是创建一个 xml 元素,我可以在其中使用变量作为属性名称和属性值

from lxml import etree

attribute = "state"
attribute_value = "NJ"
root = etree.Element()
root.append(etree.Element("Entry1", attribute = attribute_value))

然而,它只是忽略了属性是一个值为 "state" 的变量这一事实,而是将属性命名为 "attribute".

我对 Python 和 lxml 都没有经验。我查看了文档并在此处搜索了一些答案,但找不到任何类似的东西。感谢您的帮助。

如果你想传递一个动态参数给函数,你应该使用python参数解包:https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists

使用**将字典解包为函数参数:

function_name(**arguments_dict)

这是您需要的代码

from lxml import etree

attribute_name = "state"
attribute_value = "NJ"
attributes = {attribute_name: attribute_value}

root = etree.Element('root')
root.append(etree.Element("Entry1", **attributes))

print(etree.tostring(root))