2017-11-01 15 views
0

Excelのスプレッドシートにある情報から.xmlファイルを動的に作成しようとしています。Python lxmlライブラリ、変数を属性名として持つ要素を作成

基本的に私は何をしようとしているが、それだけで、実際にその属性を無視しているしかし、私は属性の名前と属性

from lxml import etree 

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

の値のための変数を使用できるXML要素を作成しています値が "state"の変数であり、代わりに属性 "attribute"の名前を付けています。

私はPythonと特にlxmlの両方で慣れていません。私はドキュメントを見て、ここでいくつかの答えを探しましたが、類似するものは何も見つかりませんでした。助けてくれてありがとう。

+0

あなたのコード全体を投稿できますか? – yash

答えて

0

あなたが機能するために、動的引数を渡したい場合は、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)) 
+0

これはうまくいきました、ありがとうございます! – Jcole

関連する問題