Search code examples
pythonxmlxml-generation

xml.etree.ElementTree how can i add attribute inside of a node?


I want the build an xml file and i made some research. I decided the use xml tree but i couldn't manage the use it like i want.

I want the generate this xml.

<Invoice test="how can i generate this ?">

</Invoice>

i am doing in 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)

It's generate xml file look like:

<Invoice />test="how can i generate this ?"

I know i shouln't use tail for i want. But i can't find a way for the make a xml look like what i want. Thank you for help.


Solution

  • This piece of XML structure is called "attribute".
    You can get it using the set(attr, value) method.

    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')
    

    test.xml:

    <Invoice test="how can i generate this ?" />