【问题标题】:xml.etree.ElementTree how can i add attribute inside of a node?xml.etree.ElementTree 如何在节点内添加属性?
【发布时间】:2022-09-22 22:16:12
【问题描述】:

我想要构建一个 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 看起来像我想要的样子的方法。谢谢你的帮助。

    标签: python xml xml-generation


    【解决方案1】:

    这段 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 ?" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多