Question

working on creating an XML file with some data using Python. I am trying to set values in dictionary to data in the list. I am going to be making multiple lines, so that is why I reference each value this way. Thanks guys. Here is my code:

from xml.etree import ElementTree as ET

root = ET.Element("painter")
root.set('version', '1.0')
linenum = 0
pointnum = 0

smpl_data = [[[20,40],(0,0,1,1)],[[10,50],(0,0,1,1)],[[78,89],(0,0,1,1)]]

while linenum <= len(smpl_data): #smpl_data change to self.lines
    elem_line = ET.SubElement(root,"line" + str(linenum), attrib={"r": "1", "g": "2", "b": "3", "a": "4"})
    print elem_line
    print elem_line.attrib.get("r")                       
    print elem_line.attrib.set("r", "smpl_data[linenum][2]")  
    # I get an attribute error: 'dict' object has no  attribute 'set'

It is clearly shown in the documentation though...

http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set

Thanks for the help.

Was it helpful?

Solution

You are calling get() and set() on the attrib member of the Element. attrib is a regular old Python dictionary that does not have a set() function. The documentation you linked is for the set() function on the actual Element object itself.

To set a value in attrib member you would use:

elem_line.attrib['r'] = smpl_data[linenum][2]

If you want to use the Element instead:

elem_line.get('r')
elem_line.set('r', smpl_data[linenum][2])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top