繁体   English   中英

xml.etree.ElementTree 如何在节点内添加属性?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM