![](/img/trans.png)
[英]Add attribute to an Element of xml.etree.ElementTree and make serializable to XML
[英]xml.etree.ElementTree how can i add attribute inside of a node?
我想要構建一個 xml 文件,我做了一些研究。 我決定使用 xml 樹,但我無法像我想要的那樣管理它的使用。
我想要生成這個 xml。
<Invoice test="how can i generate this ?">
</Invoice>
我在 python
import xml.etree.ElementTree as gfg
def GenerateXML(fileName):
root = gfg.Element("Invoice")
root.tail = 'test="how can i generate this ?"'
tree = gfg.ElementTree(root)
with open(fileName, "wb") as files:
tree.write(files)
它生成的 xml 文件如下所示:
<Invoice />test="how can i generate this ?"
我知道我不應該使用 tail 我想要的。 但我找不到讓 xml 看起來像我想要的樣子的方法。 謝謝你的幫助。
這塊XML結構叫做“屬性”。
您可以使用set(attr, value)
方法獲取它。
import xml.etree.ElementTree as gfg
def GenerateXML(fileName):
root = gfg.Element("Invoice")
root.set('test', 'how can i generate this ?')
tree = gfg.ElementTree(root)
with open(fileName, "wb") as files:
tree.write(files)
GenerateXML('test.xml')
測試.xml:
<Invoice test="how can i generate this ?" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.