I successfully added a new node to an Element using PY's ElementTree. I now try to give it attributes, which fails, despite I'm following the tutorial.
my example xml:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<level01>
<level02>
<level03>
<level04>
<node q="3,4,5,7,8" p="zen"/>
<node q="a,s,e,o,l" p="zen"/>
</level04>
</level03>
# >> here will be the new node, called <subi/> <<
<level03>
<level04>
<node q="x,y" p="zen"/>
<node q="xxx,yyy" p="zen"/>
</level04>
</level03>
</level02>
</level01>
</xml>
The node is created like this:
subi = ETL.SubElement(root[0][0][1][0][0], 'subi')
which works, it can then be accessed via root001000 and it's tag can be read.
but I fail trying to add attributes.
I tried using the syntax I found in another thread here: (with my names ofc)
>>> myattributes = {"size": "small", "gender": "unknown"}
>>> child = ET.SubElement(parent, "child", attrib=myattributes, age="10" )
Also I tried it directly, like
subi = ETL.SubElement(root[0][0][1][0][0], 'subi', attrib={"size": "small", "gender": "unknown"})
Results are always
root[0][0][1][0][0][0].tag
'subi'
but
root[0][0][1][0][0][0].attrib
{}
I also found how lxml does it, but this does not work with elementtree
#Any keyword arguments of the form name=value that you supply to the constructor are added #to the element's attributes. For example, this code:
newReed = etree.Element('reed', pitch='440', id='a4')
#will produce an element that looks like this:
<reed pitch='440' id='a4'/>
What am I doing wrong? How can I do it right? Is there a way to make elementtree do it? Or do I have to use lxml? (which would be dispreferred) ?
SubElement(parent,tag,attrib={name:key})
syntax works fine for me (Python 2.7.5). Can you provide an example against a short two level XML doc, the exact insertion code and the resulting XML output? – Boating